cult3

Laravel 4 Migrations

May 06, 2013

Table of contents:

  1. What are Migrations?
  2. Using Migrations in Laravel 4
  3. Setting up the database
  4. Installing Laravel 4 Generators
  5. How do Migrations work?
  6. Creating a Migration
  7. The anatomy of a Migration
  8. Read more about Laravel Migrations

If you have ever worked on a big project with multiple developers, you will probably have found that keeping everyone’s database structure consistent can be a nightmare.

For example, say one of your colleagues adds a new feature, and in doing so, is required to add a new column to the database. They commit their code to Git and then push it to the repo. The next time you go to work on the project you pull the latest code down but you end up with a load of errors and a broken application because your database schema is now out of date.

Passing around a SQL dump is a horrible makeshift solution and it is totally inadequate for updating the production server because it causes downtime and things can go wrong due to human error.

Fortunately, Migrations are the answer to all of these problems.

What are Migrations?

Migrations are essentially a way to version control your database. Migrations are a series of timestamped instructions for making changes to your database. This allows you to record the changes you make to the schema so anyone else can simply run the instruction file to update their version of the database to keep things consistent. It also allows you to roll back any changes you have made to a database in the event that you made a mistake.

Even if you aren’t working with other developers, Migrations are really an essential part of building an application because it means you no longer have to write SQL or deal with a janky interface like phpMyAdmin. It also makes shipping live code much less stressful because you don’t have to worry about making changes to the live database.

If you have never used Migrations before, it can be kind of weird to think that you need them. But in all honesty, once you start using them, you will never go back.

Using Migrations in Laravel 4

Laravel 4 comes ready with Migrations out of the box. Using the artisan command line interface you can create new migrations just by running a single command.

However, in this tutorial we will be making our lives even easier by installing a fantastic package for Laravel Generators.

So here’s how to set up Migrations in Laravel 4.

Setting up the database

The first thing we need to do is to set up the database. Laravel provides you with a simple configuration file to save your database details, username and password.

Firstly, set up a new local database and create a new user. Next go to app/config/database.php and fill in your database details in the connections array.

'mysql' => array(
    'driver' => 'mysql',
    'host' => 'localhost',
    'database' => 'cribbb',
    'username' => 'cribbb',
    'password' => ",
    'charset' => 'utf8',
    'collation' => 'utf8_unicode_ci',
    'prefix' => ",
),

Notice how easy it is to switch the type of database that you are using. All you would have to do is to change the default value.

Installing Laravel 4 Generators

Although Laravel 4 comes with Migrations out of the box, we can make them even easier by using the Laravel 4 Generator package by Jeffrey Way.

First, open up your composer.json and add the Laravel 4 Generator package as a requirement:

{
    "require": {
        "laravel/framework": "4.0.*",
        "way/generators": "dev-master"
    }
}

Next, update Composer from the Terminal:

$ composer update

Finally, go into app/config/app.php and add the following line at the end of the providers array:

"Way\Generators\GeneratorsServiceProvider";

Now if you run php artisan from the command line you should see the new generator tasks.

How do Migrations work?

Migrations are basically just a set of timestamped instruction files that can be automatically run to modify a database. A migration file contains a class which have a series of SQL based methods for adding tables, updating columns or dropping a table all together.

In the migration file you will find an up method and a down method. This allows the migration file to make changes to a database, but also roll back those changes if it is required.

When a migration is run, it is recorded in a special migrations table in your database. This means Laravel knows which migrations have already run, and which are still needed to run to bring the database up to speed.

To create the migrations table, run the following command from Terminal:

$ php artisan migrate:install

If you now look in your database, you should see the new migrations table.

Creating a Migration

Cribbb is going to be a social application so we need a table to store details of our users. In order to do that, we need to create a migration to create the users table.

To create the Migration, run the following line from the command line:

$ php artisan generate:migration create_users_table -fields="email:string, username:string, password:string"

Now if you look under the app/database/migrations directory, you should see the new timestamped Migration file.

The anatomy of a Migration

When you run the Migration command above, Laravel will understand that you want to create a table called users. The fields option allows us to create fields for the table, in this case two fields called email and password which are both VARCHAR (which just means string).

Now if you look in the generated Migration file, you should have the following:

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create("users", function (Blueprint $table) {
            $table->increments("id");
            $table->string("email");
            $table->string("username");
            $table->string("password");
            $table->timestamps();
        });
    }

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

Basically, all a Migration is, is a class with up and down methods. When the Migration is run, the instructions in the up method are run. When the Migration is rolled back, the instructions in the down method are run.

As you can see in this case, the up method creates the table and the default fields as well as the email and passwords fields that we specified from the command line. In the down method, the Migration will simply drop the table from the database.

If you run the migrate command now from the Terminal, Laravel will create the users table for you:

php artisan migrate

Read more about Laravel Migrations

See, how easy was that? Now that you have simple version control for your database, other developers can easily get started working on your project and rolling out changes to the server will be a breeze.

To read more about Laravel Migrations, take a look at the following articles as well as as the Laravel 4 documentation.

This tutorial is the second in a series of posts showing you how to build an entire web application from scratch. All of the tutorials will be free to web and you see all of the code up on GitHub.

Philip Brown

@philipbrown

© Yellow Flag Ltd 2024.