Database Migrations In Laravel 4

Laravel 4 developed by Taylor Otwell, is indeed a great php framework out there. It is suitable for both small and large scale applications, and has a very active community of really helpful people. I started using laravel more or less four months ago, and I have not searched google for “the best php framework” since then. With its powerful components like: a powerful and flexible routing system, an expressive query builder Fluent, Eloquent ORM, a descent authentication component, an intelligent IoC Container, Blade template engine and Artisan CLI tool, it just rocks (pardon me if I am missing something here).

Database Migrations In Laravel

Database migrations in Laravel provide you with an easy way of managing your application’s database schema. When using migrations, a lot of tasks related to database schema become a lot easier; by using migrations you can change the structure of database tables on the fly, they can keep record of your previous changes and allow you to migrate to any state at any time.

Setting Up Migrations

Before we can create our first migration, we need to initialize the migration repository inside our database, we can do this by entering artisan migrate:install command on terminal:

(Don’t forget to change your working directory to the root of your Laravel installation.)

┌─[usm4n@usm4n-desktop]―[~/laravel4]
└─•artisan migrate:install
Migration table created successfully

Creating Database Tables Using Migrations

Now, suppose we want to create an ‘articles’ database table for our application, the first thing we need to create is, an Articles class (actually you can use any name) by extending Laravel’s Migration class inside app/database/migrations directory.

Do not panic, we can do this by using artisan migrate:make articles --table=articles command:

┌─[usm4n@usm4n-desktop]―[~/laravel4]
└─•artisan migrate:make articles --table=articles
Created Migration: 2013_11_11_223728_articles
Generating optimized class loader

The ‘2013_11_11_223728’ part of the filename is a timestamp, which is internally used by the migration system to keep track of changes. So, it is recommended that you should always use the above command to create your Migration classes.

The generated code inside this file will look like this:

<?php
//app/database/migrations/2013_11_11_223728_articles.php

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

class Articles extends Migration {
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('articles', function(Blueprint $table)
        {
            //
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('articles', function(Blueprint $table)
        {
            //
        });
    }
}

To actually commit changes to database, we use artisan migrate command, which in turn calls the up methods of all the Migration classes available inside app/database/migrations directory. Similarly if we want to rollback migrations, we use artisan migrate:rollback command which uses down method for its operations. So, we use up and down methods for our intended operations on table schema.

Here is a short reference of Schema related functions that Laravel provides:

Command Description
$table->increments('id'); Incrementing ID to the table (primary key).
$table->string('email'); VARCHAR equivalent column
$table->string('name', 100); VARCHAR equivalent with a length
$table->integer('votes'); INTEGER equivalent to the table
$table->float('amount'); FLOAT equivalent to the table
$table->boolean('confirmed'); BOOLEAN equivalent to the table
$table->timestamps(); Adds created_at and updated_at columns
$table->text('description'); TEXT equivalent to the table
->nullable() Designate that the column allows NULL values
->default($value) Declare a default value for a column
->unsigned() Set INTEGER to UNSIGNED

For a complete list of functions visit Laravel’s official documentation site. Now, consider the following revised code:

<?php

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

class Articles extends Migration {

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('articles', function(Blueprint $table)
        {
            $table->create();  // creates the table.
            $table->increments('id'); 
            $table->string('title',50); 
            $table->string('description');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('articles', function(Blueprint $table)
        {
            //
        });
    }

}

After making the above changes in migration file, all we need is to run artisan migrate command on terminal, and it will create the following table for us:

mysql> describe articles;
+-------------+------------------+------+-----+---------------------+----------------+
| Field       | Type             | Null | Key | Default             | Extra          |
+-------------+------------------+------+-----+---------------------+----------------+
| id          | int(10) unsigned | NO   | PRI | NULL                | auto_increment |
| title       | varchar(50)      | NO   |     | NULL                |                |
| description | varchar(255)     | NO   |     | NULL                |                |
| created_at  | timestamp        | NO   |     | 0000-00-00 00:00:00 |                |
| updated_at  | timestamp        | NO   |     | 0000-00-00 00:00:00 |                |
+-------------+------------------+------+-----+---------------------+----------------+
5 rows in set (0.00 sec)

Rolling Back Migrations

As I wrote earlier, artisan migrate:rollback uses down method of Migration classes to undo any changes made by last artisan migrate command. So, whatever we do inside up method, the inverse of it goes inside down method.

Consider the following migration:

<?php

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

class ChangeDescription extends Migration {

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('articles', function(Blueprint $table)
        {
            $table->renameColumn('description','explanation');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('articles', function(Blueprint $table)
        {
            $table->renameColumn('explanation','description');
        });
    }

}

When we will run this migration using artisan migrate command, the ‘description’ column will be renamed as ‘explanation’. Similarly, running artisan migrate:rollback will revert this change by restoring the name of ‘explanation’ column back to ‘description’. Simple huh?

3 thoughts on “Database Migrations In Laravel 4”

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.