How to use Laravel’s migration feature

The first step is to run the artisan command:

$ php artisan migrate:install

This will create a table named migration, which has two columns: migration, which is a varchar 255 in MySQL, and batch, which is an integer. This table will be used by Laravel to keep track of which migrations have been run. In other words, it maintains a history of all of the operations that have been performed. The following is a list of the main operations:

  • install: As mentioned earlier, this operation installs
  • refresh: This operation resets and reruns all of the migrations
  • reset: This operation rolls back all of migrations
  • rollback: This operation is a type of “undo”, and simply rolls back the last operation
  • status: This operation produces a table-like output of the migrations and states whether or not they have been run

An example of migration

Laravel 5 contains two migrations in the /database/migrations directory.

The first migration creates the users table.

The second one creates the password_resets table, which, as you may have guessed, is used to recover lost passwords. Unless specified, the migrations operate on the database that is configured in the /config/database.php configuration file:

<?php

use IlluminateDatabaseSchemaBlueprint;
use IlluminateDatabaseMigrationsMigration;

class CreateUsersTable extends Migration {

  /**
   * Run the migrations.
   *
   * @return void
   */
  public function up()
  {
    Schema::create('users', function(Blueprint $table)
    {
      $table->smallIncrements('id')->unsigned();
      $table->string('name');
      $table->string('email')->unique();
      $table->string('password', 60);
      $table->rememberToken();
      $table->timestamps();
      $table->softDeletes();
    });
  }

  /**
   * Reverse the migrations.
   *
   * @return void
   */
  public function down()
  {
    Schema::drop('users');
  }

}

Migrations extend the Migration class and use the Blueprint class.

There are two methods: up and down, which are used when the migrate commands and the rollback commands are used, respectively. The Schema::create() method is called with the table name as the first parameter and a function callback as the second parameter, which accepts an instance of a Blueprint object as a parameter.

Creating the table

The $table object has a few methods that perform tasks such as creating indexes, setting up auto-increment fields, stating which type of fields should be created, and passing the name of the field as a parameter.

The first command is used to create an auto-increment field id, which will be the primary key of the table. Then, string fields, such as name, email, and password are created. Note that the unique method is chained to the create statement for the email field, stating that the email field will be used as the login name/user ID, as this is a common practice in most modern web applications. The rememberToken is used to allow the user to remain authenticated per each session. This token gets reset on each login and logout, protecting the user from a potentially malicious hijacking attempt.

The Laravel migration magic

Laravel migrations are also capable of creating timestamp fields that are used to automatically store creation and update information for each model through its table row.

$table->timestamps();

The following line of code tells the migration to automatically create two columns in the table, namely created_at and updated_at, which is automatically used by Laravel’s Eloquent Object-relational mapping (ORM) to allow the application to know when the object was created and when it was updated:

$table->timestamps()

In the following example, the fields are updated as follows:

/*
*   created_at is set with timestamps
*/
$user = new User();
$user->email = "[email protected]";
$user->name = "John Doe";
$user->save(); // created_at is set with timestamps

/*
*   updated_at is set with timestamps
*/
$user = User::find(1); //where 1 is the $id
$user->email = "[email protected]";
$user->save(); //updated_at is updated

Another great Laravel feature is the soft delete field. This provides a type of recycle bin to allow the data to be optionally restored at a later time.

This feature simply adds another column to the table to allow soft deleting of the data. The code to be added to the migration looks like this:

$table->softDeletes();

This adds a column to the database, deleted_at, which will either have null as its value or a timestamp to indicate when the record was deleted. This builds a recycle bin feature right into your database application.

Run the following command:

$ php artisan migrate

The migration is initiated and the tables are created. The migration table now appears, as shown in the following screenshot:

$table->timestamps();

The structure of the users table is shown in the following screenshot:

$table->timestamps();

To rollback the migration, run the following command:

$ php artisan migrate:rollback

The rollback command uses the migration table to determine which actions to rollback. In this case, the migrations table, after it has been run, is now empty.

About the author

Deven Rathore

I'm Deven Rathore, a multidisciplinary & self-taught designer with 3 years of experience. I'm passionate about technology, music, coffee, traveling and everything visually stimulating. Constantly learning and experiencing new things.

Pin It on Pinterest

Shares