Lavarel — Migration & Seeding

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.

References : https://laravel.com/docs/5.6/migrations

Laravel includes a simple method of seeding your database with test data using seed classes. All seed classes are stored in the database/seeds directory. Seed classes may have any name you wish, but probably should follow some sensible convention, such as UsersTableSeeder, etc. By default, a DatabaseSeeder class is defined for you. From this class, you may use the call method to run other seed classes, allowing you to control the seeding order.

References : https://laravel.com/docs/5.6/seeding

In this tutorial, we will learn how to use laravel migrations and seeders for them. Laravel provides great functionality to create migrations which are the schema for the database. Laravel also provides seeder which is very helpful for creating dummy data. This dummy data is very useful for testing purposes.

Setting Up Migrations

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

In this tutorial, we will a create migration for a products, categories and product_category

A product has some categories, let’s create a migration for Category table, To create a new migration file, use the make:migration {migration_file_name} -create={table_name} by Artisan command :

php artisan make:migration create_category_table –create=categories

Open the categories table migration file present in the database/migrations directory. Replace the contents of the file with the contents present below.

<?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');
}
}

A migration class contains two methods: up and down. The up method is used to add new tables, columns, or indexes to your database, while the down method should reverse the operations performed by the up method.

To create new columns in a table, whether in a create table call or a modify table call, use the instance of Blueprint that’s passed into your closure:

Schema::create('categories', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->text('description');
$table->timestamps();
});

Let’s look at the various methods available on BluePrint instances for creating columns here : https://laravel.com/docs/5.6/migrations#columns

Let’s create a migration for the products table by running the following command.

php artisan make:migration create_product_table — create=products

Open the products table migration file present in the database/migrations directory. Replace the contents of the file with the contents present below.

<?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');
}
}

Finally create a migration for the product-category table by running the following command.

php artisan make:migration create_product_category_table — create=product_category

Open the product_category table migration file present in the database/migrations directory. Replace the contents of the file with the contents present below.

<?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');
}
}

You can create some more migrations like a migration for the attributes, images, brands, stocks, comments, etc table. But for the sake of this tutorial, we will create a simple like above.

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

After run this command, you will receive message like following :

Migrating: 2018_07_27_161708_create_product_table
Migrated: 2018_07_27_161708_create_product_table
Migrating: 2018_07_27_130104_create_category_table
Migrated: 2018_07_27_130104_create_category_table
Migrating: 2018_08_10_120731_create_product_category_table
Migrated: 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

You may rollback a limited number of migrations by providing the step option to the rollback command. Fo example, the following command will rollback the last file migrations:

php artisan migrate:rollback — step=5

Then you can open any table migration file present in the database/migrations directory And add more columns. After finish, Run the following command to migrate the database.

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 CategoriesTableSeeder
php artisan make:seeder ProductsTableSeeder
php artisan make:seeder ProductCategoryTableSeeder

Open the CategoriesTableSeeder seeder file present in the database/seeds directory. Replace the contents of the file with the contents present below.

<?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.',
],
]);
}
}

Open the ProductsTableSeeder seeder file present in the database/seeds directory. Replace the contents of the file with the contents present below.

<?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,
],
]);
}
}

Open the ProductCategoryTableSeeder seeder file present in the database/seeds directory. Replace the contents of the file with the contents present below.

<?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,
],
]);
}
}

Now, go to the DatabaseSeeder.php file located in database/seeds directory and replace the run function with the code present below.

<?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,
]);
}
}

Of course, manually specifying the attributes for each model seed is cumbersome. Instead you can use model factories to conveniently generate large amounts of database records.

Reference : https://laravel.com/docs/5.6/seeding#using-model-factories

Running Seeders

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

composer dump-autoload

Now, that our database migrations and seeder are created. Run the command below to seed the database

php artisan db:seed

By default, the db:seed command runs the DatabaseSeeder class, which may be used to call other seed classes. However, you may use the –class option to specify a specific seeder class to run individually :

php artisan db:seed –class= CategoriesTableSeeder
php artisan db:seed –class= ProductTableSeeder
php 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.

Hopefully, now you have a good understanding of how to work with database seeders.


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