Laravel Migrations

Lesson 22 of 50 - Learn how to create, modify, and manage database tables using Laravel migrations.

44%
1. What Are Laravel Migrations?

Laravel migrations are files used to create and modify database structures, such as tables and columns, using PHP.

Instead of manually creating tables in phpMyAdmin, you can use migrations.

Benefits of migrations:

  • Create database tables using PHP code.
  • Add or remove table columns.
  • Track database structure changes.
  • Share database changes with other developers.
  • Manage schema changes in version control.

Laravel stores migration files in the database/migrations directory.

2. Create Your First Migration

Use the Artisan command to create a migration for a students table.

php artisan make:migration create_students_table

Laravel creates a new migration file inside database/migrations.

Open the generated file and define the table structure:

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('students', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamps();
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('students');
    }
};

The up() method creates the table, while down() reverses that migration.

3. Run Migrations

After defining the migration, run the following command:

php artisan migrate

Laravel executes pending migrations and creates the students table.

To check migration status, run:

php artisan migrate:status

Laravel records executed migrations in the database's migrations table.

Before running migrations, make sure your database connection is correctly configured in the .env file.

4. Common Column Types

Laravel's schema builder provides methods for defining common database column types.

Schema::create('students', function (Blueprint $table) {
    $table->id();

    $table->string('name');
    $table->text('address')->nullable();
    $table->integer('age');
    $table->decimal('fee', 10, 2);
    $table->boolean('is_active')->default(true);
    $table->date('admission_date');

    $table->timestamps();
});

Explanation:

  • id() creates an auto-incrementing primary key.
  • string() creates a string column.
  • text() stores longer text.
  • integer() stores integer values.
  • decimal() stores decimal numbers, useful for fees.
  • boolean() stores a true/false value.
  • date() stores a date.
  • timestamps() creates created_at and updated_at.

This is an alternative table definition. Use the columns appropriate for your actual application.

5. Add Columns to an Existing Table

To add a column to an existing table, create another migration.

php artisan make:migration add_phone_to_students_table

Update the generated migration:

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        Schema::table('students', function (Blueprint $table) {
            $table->string('phone')->nullable();
        });
    }

    public function down(): void
    {
        Schema::table('students', function (Blueprint $table) {
            $table->dropColumn('phone');
        });
    }
};

Run the migration:

php artisan migrate

The new migration adds a nullable phone column to the existing students table.

6. Modify and Rename Columns

You can rename a column by creating a new migration.

php artisan make:migration rename_phone_in_students_table

Example migration:

Schema::table('students', function (Blueprint $table) {
    $table->renameColumn('phone', 'mobile');
});

The example assumes the phone column already exists.

To change an existing column's type or properties, Laravel provides methods such as change(). Database support and additional requirements can vary by Laravel version and database engine.

Schema::table('students', function (Blueprint $table) {
    $table->string('name', 150)->change();
});

Always review the generated SQL and test schema changes before applying them to a production database.

7. Roll Back Migrations

Laravel allows you to roll back the most recent migration batch.

php artisan migrate:rollback

To roll back a limited number of migration steps:

php artisan migrate:rollback --step=1

To see which migrations have run, use:

php artisan migrate:status

Rolling back executes the relevant migration's down() method. Depending on the migration, this may delete tables, columns, or data.

Review the rollback code and back up important data before using rollback commands.

8. Foreign Keys and Relationships

Foreign keys connect records between related tables. For example, each student may belong to a course.

Schema::create('courses', function (Blueprint $table) {
    $table->id();
    $table->string('course_name');
    $table->timestamps();
});

Schema::create('students', function (Blueprint $table) {
    $table->id();
    $table->string('name');

    $table->foreignId('course_id')
          ->constrained('courses')
          ->cascadeOnDelete();

    $table->timestamps();
});

In this example, course_id references the primary key of the courses table.

cascadeOnDelete() means deleting a course can also delete its related students at the database level. Use cascading deletes only when that behavior is appropriate for your application.

Create the referenced table before the table that depends on it, and roll back dependent tables in the appropriate order.

9. Migration Commands and Practical Assignment

Useful migration commands:

Command Purpose
php artisan make:migration create_students_table Create a migration file.
php artisan migrate Run pending migrations.
php artisan migrate:status View migration status.
php artisan migrate:rollback Roll back the latest migration batch.
php artisan migrate:fresh Drop all tables and rerun migrations.

Practical Assignment:

  1. Create a migration for a students table.
  2. Add name, email, phone, age, and fee columns.
  3. Make email unique and phone nullable.
  4. Run the migration and inspect the table in phpMyAdmin.
  5. Create a second migration to add an address column.
  6. Create a courses table and add a foreign key to students.
  7. Practice checking migration status and rolling back a test migration.

Warning: php artisan migrate:fresh drops all tables on the selected connection before recreating them. Never run it on a database containing important data unless you intentionally want to erase that data.

Quick Quiz

1. Where are Laravel migration files stored?




2. Which method defines the operations performed when a migration runs?




3. Which command runs pending migrations?