migration


Migrations allow us to easily modify and share the application's database schema. It provides support for creating and manipulating tables across all of Laravel's supported database systems.

Generating Migrations

Artisan command make:migration creates a migration file.

php artisan make:migration create_users_table

Each migration file contains a timestamp which allows Laravel to determine the order of the migrations.

The --table and --create options can also be used to indicate the name of the table and whether the migration will be creating a new table.

php artisan make:migration create_users_table --create=users

php artisan make:migration add_orders_to_users_table --table=users

Migration Structure

A migration class contains two methods: up and down. The up method is used to add new table, columns or indexes to the database while the down method will reverse the operations performed by the up method. We can use the Laravel schema builder to create and modify tables.

public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('email');
        $table->string('password');
        $table->timestamps();
    });
}

public function down()
{
    Schema::drop('users');
}

Running Migrations

Artisan command migrate runs the database migration.

php artisan migrate

Migrations Roll back

Artisan command migrate:rollback can be used to rollback the latest migration operation that rolls back the last batch of migrations which may include multiple migration files.

php artisan migrate:rollback

You can rollback a limited number of migrations by providing the step option to the rollback command.

php artisan migrate:rollback --step=5

The migrate:reset command will roll back all of your application's migrations.

php artisan migrate:reset

ROLL BACK & MIGRATE SINGLE COMMAND

Artisan command migrate:refresh will roll back all of your migrations and then execute the migrate command effectively re-creating the entire database.

php artisan migrate:refresh

// Refresh the database and run all database seeds...
php artisan migrate:refresh --seed

You can rollback & re-migrate a limited number of migrations by providing the step option to the refresh command.

php artisan migrate:refresh --step=5

CREATING TABLES

To create a new database table, use the create method on the Schema facade. The create method accepts two arguments the name of the table and a closure which receives a Blueprint object that can be used to define the new table.

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

RENAMING & DROPPING TABLES

The rename method can be used to rename an existing database table.

Schema::rename($from, $to);

You can use the drop or dropIfExists method to drop an existing table.

Schema::drop('users');
Schema::dropIfExists('users');

CREATING COLUMNS

The table method on the Schema facade can be used to update existing tables.

Schema::table('users', function (Blueprint $table) {
    $table->string('email');
});

Some of the most used column types are listed below.

COLUMN TYPES DESCRIPTION
$table->increments('id'); Incrementing ID (primary key) using a "UNSIGNED INTEGER" equivalent.
$table->string('email'); VARCHAR equivalent column.
$table->string('name', 100); VARCHAR equivalent with a length.
$table->text('description'); TEXT equivalent for the database.
$table->longText('description'); LONGTEXT equivalent for the database.
$table->softDeletes(); Adds nullable deleted_at column for soft deletes.
$table->integer('phone_number'); INTEGER equivalent for the database.
$table->enum('status', ['on', 'off']); ENUM equivalent for the database.
$table->rememberToken(); Adds remember_token as VARCHAR(100) NULL.
$table->time('time'); TIME equivalent for the database.
$table->date('date'); DATE equivalent for the database.
$table->timestamp('created_at'); TIMESTAMP equivalent for the database.

CREATING INDEXES

To create the index, we can chain the unique method onto the column definitions. Supported index types are primary, unique and index.

$table->string('email')->unique();

DROPPING INDEXES

You need to specify the index's name. Concatenate the table name, the index type and the name of the indexed column to drop an index.

$table->dropPrimary('users_id');
$table->dropUnique('email');
$table->dropIndex('username');

SEEDING

Laravel allows to seed the database with test data using seed classes. All seed classes are stored in the database/seeds directory. By default, a DatabaseSeeder class is defined from where you can call methods to run other seed classes, allowing you to control the seeding order.

WRITING SEEDERS

Artisan command make:seeder can be used to generate a seeder.

php artisan make:seeder UsersTableSeeder

A seeder class only contains one method by default: run. This method is called when the db:seed Artisan command is executed. You may use the query builder to manually insert data or you may use Eloquent model factories.

public function run()
{
    DB::table('users')->insert([
        'name' => str_random(10),
        'email' => str_random(10).'@gmail.com',
        'password' => bcrypt('secret'),
    ]);
}

ADDITIONAL SEEDERS

Within the DatabaseSeeder class, you can use the call method to execute additional seed classes. Using the call method allows you to break up your database seeding into multiple files so that no single seeder class becomes overwhelmingly large.

public function run()
{
    $this->call(UsersTableSeeder::class);
    $this->call(PostsTableSeeder::class);
    $this->call(CommentsTableSeeder::class);
}

RUNNING SEEDERS

You can use the db:seed Artisan command to seed your database. The db:seed command runs the DatabaseSeeder class which can be used to call other seed classes. However, you may use the --class option to specify a specific seeder class to run individually.

php artisan db:seed

php artisan db:seed --class=UsersTableSeeder

You may also seed your database using the migrate:refresh command, which will also rollback and re-run all of your migrations. This command is useful for completely re-building your database.

php artisan migrate:refresh --seed