So far, we have created some base models and the general outline of the database. Now, we need to create database migrations and seeding. Traditionally, database "dump" files have been used as a way to pass around both the schema, which is the structure of the tables, and the data, which would be the initial or predefined records, such as default values; unchanging lists, such as cities or countries; and users such as "admin". These dump files that contain SQL can be committed to source code control. This is not always the best way to maintain the integrity of the database; since every time a developer adds records or modifies the database, all of the developers in the team would need to drop and recreate the database or add or delete the data, tables, rows, columns, or indexes manually. Migrations allow the database to live in the form of code, actually residing inside the Laravel project, as well as to be versioned within source code control.
Migrations are run from the command line and can also be automated to automatically create the database, whenever required if it doesn't already exist, or drop and recreate the tables and populate the tables if they already exist. Migrations have existed for a while in Laravel, so their presence in Laravel 5 is not surprising.
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 installsrefresh
: This operation resets and reruns all of the migrations reset
: This operation rolls back all of migrationsrollback
: This operation is a type of "undo", and simply rolls back the last operationstatus
: This operation produces a table-like output of the migrations and states whether or not they have been runLaravel 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.
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.
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.
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:
The structure of the users
table is shown in the following screenshot:
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.