Lavarel — Migration & Seeding

Dai Tranvan
Sep 4, 2018 · 7 min read

Introduction Migration and Seeding

Migrations are like version control for your database, allowing your team to easily modify and share the application’s database schema. Migrations are typically paired with Laravel’s schema builder to easily build your application’s database schema. If you have ever had to tell a teammate to manually add a column to their local database schema, you’ve faced the problem that database migrations solve.

Setting Up Migrations

The database Migration table will keep track of which migrations you have and have not run

php artisan make:migration create_category_table –create=categories
<?php

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

class CreateCategoryTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('categories', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->text('description');
$table->timestamps();
});
}

/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('categories');
}
}
Schema::create('categories', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->text('description');
$table->timestamps();
});
php artisan make:migration create_product_table — create=products
<?php

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

class CreateProductTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->increments('id');
$table->string('sku')->unique();
$table->string('title');
$table->text('description');
$table->float('price');
$table->timestamps();
});
}

/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('products');
}
}
php artisan make:migration create_product_category_table — create=product_category
<?php

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

class CreateProductCategoryTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('product_category', function (Blueprint $table) {
$table->integer('product_id');
$table->integer('category_id');
$table->primary(['product_id', 'category_id']);
});
}

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

Migration the database

Now that we have created migrations, let’s migrate them to the database. Run the following command to migrate the database.

php artisan migrate
Migrating: 2018_07_27_161708_create_product_tableMigrated: 2018_07_27_161708_create_product_tableMigrating: 2018_07_27_130104_create_category_tableMigrated: 2018_07_27_130104_create_category_tableMigrating: 2018_08_10_120731_create_product_category_tableMigrated: 2018_08_10_120731_create_product_category_table

Rolling Back Migrations

If you forgot create any column, we can rollback the lastest migration operation (Migrations table in database will keep track of which migrations you have and haven’t run), we may use the rollback command. This command rolls back the last “batch” of migrations, which may include multiple migration files :

php artisan migrate:rollback
php artisan migrate:rollback — step=5
php artisan migrate

Creating Database Seeders

Now that we have created database migrations, let’s create seeder for the categories, products and product_category table. To create a new seeder file, use the make:seeder {seeder_file_name} by Artisan command, Run the following command to create it.

php artisan make:seeder CategoriesTableSeederphp artisan make:seeder ProductsTableSeederphp artisan make:seeder ProductCategoryTableSeeder
<?php

use Illuminate\Database\Seeder;

class CategoriesTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
DB::table('categories')->insert([
[
'title' => 'Dresses',
'description' => 'The The Dress Shop event is over, but there is still more to discover.',
],
[
'title' => 'Jewelry',
'description' => 'The Fashion Week | Your fashion, your style event is over, but there is still more to discover.',
],
[
'title' => 'Sunglasses',
'description' => 'The Sunglasses with Free Shipping event is over, but there is still more to discover.',
],
]);
}
}
<?php

use Illuminate\Database\Seeder;

class ProductTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
DB::table('products')->insert([
[
'sku' => 'P0001',
'title' => 'Hot Women Holiday Strappy Button Pocket Ladies Summer Beach Midi Swing Sun Dress',
'description' => 'It is made of high quality materials,durable enought for your daily wearing. Stylish and fashion make you more attractive',
'price' => 7.98,
],
[
'sku' => 'P0002',
'title' => 'Womens Vintage Boho Long Maxi Evening Party Dress Summer Casual Beach Sundress',
'description' => 'It is a Summer Must have and a statement piece that will turn heads. Beautiful and high quality dress,Full Length, Chiffon Material',
'price' => 7.95,
],
[
'sku' => 'P0003',
'title' => 'Diamond Jewel 14K Gold Round Diamond Stud Earrings',
'description' => 'The weight of a precious stone and easiest way to measure a diamond.One carat is equal to 200 miligrams.',
'price' => 799,
],
[
'sku' => 'P0004',
'title' => 'Diamond Jewel 14K Gold Round Diamond Stud Earrings',
'description' => 'The weight of a precious stone and easiest way to measure a diamond.One carat is equal to 200 miligrams.',
'price' => 799,
],
[
'sku' => 'P0005',
'title' => 'J+S Premium Military Style Classic Aviator Sunglasses, Polarized, 100% UV protection',
'description' => 'POLARIZED LENS, UV 400 PROTECTION, HIGH QUALITY FRAME, PERFECT ALL ROUNDER, 100% RISK FREE PURCHASE',
'price' => 16.99,
],
]);
}
}
<?php

use Illuminate\Database\Seeder;

class ProductCategoryTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
DB::table('product_category')->insert([
[
'product_id' => 1,
'category_id' => 1,
],
[
'product_id' => 2,
'category_id' => 1,
],
[
'product_id' => 3,
'category_id' => 2,
],
[
'product_id' => 4,
'category_id' => 3,
],
]);
}
}
<?php

use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
/**
* Seed the application's database.
*
* @return void
*/
public function run()
{
$this->call([
CategoriesTableSeeder::class,
ProductTableSeeder::class,
ProductCategoryTableSeeder::class,
]);
}
}

Running Seeders

Once you have written your seeder, you may need to regenerate Composer’s autoloader using the dump-autoload command:

composer dump-autoload
php artisan db:seed
php artisan db:seed –class= CategoriesTableSeederphp artisan db:seed –class= ProductTableSeederphp artisan db:seed –class= ProductCategoryTableSeeder

Conclusion

In this tutorial, we looked at what migrations are, and how to use them. We also looked at database seeding. We defined a database dictionary and created migration and seed files for our database dictionary.


Why Lavarel 5 migrations and Seeds are damn powerful tools

  • Migrations are great because they allow you to track changes to how your database is set up, step by step, and update or rollback those changes. For example, if you add a new table, that’s a migration. If you drop a table, that’s a rollback on a migration. If you want to add a new column to a table, you can easily setup a migration for that, as well as a rollback to delete that extra column.
  • You don’t need to import the SQL file manually into the production database. Instead, you can just run the Artisan command to migrate your database and another command to seed it.
  • Multiple developers on the same project makes migrations an absolute essential
  • Sometimes you may want to seed your database with dynamic information. For example, if yo8u need to connect to a 3rd party API, fetch some particular data, then seed that into the database. We can’t do that with a static SQL file. Or Sometimes you just want to seed your database with procedurally generated values as well.
  • No more need for creating “testing posts” for your blog, running sql queries to fill your db with random data. Everything’s built in. With a few commands, you can :
  • — — run all migrations thus creating all tables, indices, foreign keys, and everything else.
  • — — run all seeders and populate all your tables thus be supplied with ready testing data

GREVO TechBlog

Learn more about how GREVO designs, builds, and operates our systems and engineering organizations

Dai Tranvan

Written by

GREVO TechBlog

Learn more about how GREVO designs, builds, and operates our systems and engineering organizations