Laravel4 Migrations and Seeding

Standard

So far we have created the virtual host for our laravel4 application named “thisdayinbangladesh.dev” and also set up the basic laravel4 installation. Now in this lesson we will create the migrations and seeders needed for our application.

“Migrations are a type of version control for your database. They allow a team to modify the database schema and stay up to date on the current schema state. Migrations are typically paired with the Schema Builder to easily manage your application’s scheme.”

“Laravel also includes a simple way to seed your database with test data using seed classes.”

First thing first. Open up the Mac Terminal and enter inside the “thisdayinbangladesh” folder under MAMP’s “htdocs” directory. All of the following commands should be executed from inside the project folder.

Create migration files for all of our currently needed tables:
Execute these commands one by one,

php artisan migrate:make create_days_table --table=days --create
php artisan migrate:make create_facts_table --table=facts --create
php artisan migrate:make create_types_table --table=types --create
php artisan migrate:make create_fact_type_table --table=fact_type --create

These commands set up the basic migration scripts that we’ll be using to create the database tables

Update the migration files:
Edit “database/migrations/TODAYS_FULL_DATE_create_days_table.php” file and update the “up()” method to include a new column on the “days” table and to remove the “timestamp” column.

	public function up()
	{
		Schema::create('days', function(Blueprint $table)
		{
			$table->increments('id');
			$table->string('day');
		});
	}

Update the “up()” method of “database/migrations/TODAYS_FULL_DATE_create_facts_table.php” file to the following,

	public function up()
	{
		Schema::create('facts', function(Blueprint $table)
		{
			$table->increments('id');
                        $table->integer('day_id');
			$table->string('title');
                        $table->longText('description');
                        $table->timestamps();
		});
	}

Update the “up()” method of “database/migrations/TODAYS_FULL_DATE_create_types_table.php” file to the following,

	public function up()
	{
		Schema::create('types', function(Blueprint $table)
		{
			$table->increments('id');
                        $table->string('type');
		});
	}

Update the “up()” method of “database/migrations/TODAYS_FULL_DATE_create_fact_type_table.php” file to the following,

	public function up()
	{
		Schema::create('fact_type', function(Blueprint $table)
		{
			$table->increments('id');
                        $table->integer('fact_id');
                        $table->integer('type_id');
		});
	}

Prepare the Seeder files to add sample data to those tables:
Create a file within the “app/database/seeds” folder that has the same name as the table. So, for our “days” table create a file named “DayTableSeeder.php” inside “seeds” folder containing the following full code,

<?php 
class DayTableSeeder extends Seeder {
 
    public function run()
    {        
        for ($i = 1; $i <= 31; $i++) {
            for ($j = 1; $j <= 12; $j++) {
                Day::create(array(
                    'day' => sprintf("%02s", $i).'-'.sprintf("%02s", $j)
                ));             
            }
        }

    }
 
}

Here I am inserting some “day-month” patterned days rows in the “days” table using a simple loop. Please, don’t judge my PHP knowledge on this. This is not about showing optimized, minimal, smell free coding.
Also, create other seeder files for those remaining tables into which we want to push some sample data even before launching the app.
Create “FactTableSeeder.php” with following code. Here we are inserting some sample facts that holds the fact’s sample title and sample description just for checking out data retrieval with proper relations later on the next lesson.

<?php
 
class FactTableSeeder extends Seeder {
 
    public function run()
    {        
        for ($i = 1; $i <= 372; $i++) {
                Fact::create(array(
                    'day_id' => $i,
                    'title'   => 'Fact-'.$i,
                    'description' => 'Description of fact-'.$i,
                ));
        }

    }
 
}

Now create the “TypeTableSeeder.php” file with the following code,

<?php
 
class TypeTableSeeder extends Seeder {
 
    public function run()
    {        
        $types = array ('good', 'bad', 'revolutionary', 'birth', 'death');
        
        foreach ($types as $key=>$value) {
                Type::create(array(
                    'type' => $value,
                ));
        }

    }
 
}

And finally create the “FactTypeTableSeeder.php” file with,

<?php
 
class FactTypeTableSeeder extends Seeder {
 
    public function run()
    {        
        for ($i = 1; $i <= 10; $i++) {
            FactType::create(array(
                'fact_id' => $i,
                'type_id' => rand(1,5)
            ));             
        }

    }
 
}

As you can see, we are assigning some “facts” to some “types” and making rows in the “fact_type” table pairing “fact_id” with “type_id” as for our sample data.

Update the DatabaseSeeder file:
Update the “run()” method of the “DatabaseSeeder.php” file. That should already be there inside “app/database/seeds” folder with the following code,

	public function run()
	{
		Eloquent::unguard();

		$this->call('DayTableSeeder');
                $this->call('FactTableSeeder');
                $this->call('TypeTableSeeder');
                $this->call('FactTypeTableSeeder');
	}

Run Migration and Seed:
Execute the following commands one by one.

php artisan migrate
php artisan db:seed

If the commands executed successfully then you should see those tables along with an extra tables named “migrations” under your “thisdayinbangladesh” database. Also there should be our sample data in each table if the Seeding happens successfully!

Note:
As one “fact” will have multiple “types” and vise versa. You should name the Pivot table (“fact_type” in this case) of the “facts” and “types” table by taking the singular name of the alphabetically first table then the second table with an underscore in the middle.
Also there should be two columns at least, to hold the relation which should be named by taking the singular name of one table with its primary key along with an underscore in the middle. Such as “fact_id”, “type_id”.
But wait, don’t be scared. There is still flexibility while naming those tables and columns for using with Eloquent ORM. You will have to just pass those non-conventional table names or column names as parameters in corresponding methods while creating ORM relations among tables or while creating migrations tables.
We just followed the conventional naming pattern in this lesson to make thing simple and understandable.

What next?:
The next step is to make proper Routing for our application. Which is ready now!

Advertisements

2 thoughts on “Laravel4 Migrations and Seeding

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s