Migration and Data Seeding in Laravel

In this tutorial, we will learn how to create database migrations and seeders. For PHP developers, we need to have a database for a dynamic application and if we are working with a team, we all should have the same database at the same time. 

Laravel provides great functionality to create database from migrations which are the schema for the database. Migrations allow our team to easily modify and share the application’s database schema. Using migration, we don’t have to share database changes to our team mates manually, it will be done in a single command!

Creating an application

First thing first, you will need a laravel application if you don’t have one so install a fresh laravel application and go to the .env file and configure your database credentials.

Generate Migrations : 

To create a migration, we use laravel’s artisan command make:migration

To create a migration, we use laravel’s artisan command make:migration Full command is php artisan make:migration schema_name . Using this command, laravel generates a table schema with the name that you have provided in the database/migration directory.

Laravel also provides 2 options that we can use, it’s –table and –create, one will be used to indicate the name of the table and another will be used to indicate whether the migration will be creating a new table. Examples are as below:

php artisan make:migration schema_name --table=table_name
php artisan make:migration add_tag_to_users_table --create=table_name

We are having following contents in the migration file:

<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class SchemaName extends Migration
	{
	/**
	* Run the migrations.
	*
	* @return void
	*/
	public function up()
	{
		Schema::create('table_name', function (Blueprint $table) {
			$table->increments('id');
			$table->string('email_id')->unique();
			$table->string('full_name');
			$table->text('about');
			$table->timestamps();
		});
	}
	/**
	* Reverse the migrations.
	*
	* @return void
	*/
	public function down()
	{
		Schema::dropIfExists('users');
	}
}

Here, 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.

Run Migrations:

Now, we have created one migration for the users table. Run the following command to migrate the database:

php artisan migrate

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

Migrating: 2020_05_15_161708_schema_name
Migrated: 2020_05_15_161708_schema_name

Sometimes, there is a possibility of loss of data, migration command will ask for confirmation to avoid unexpected data loss, But you can override this using force option, This will execute migration without any prompt.

php artisan migrate --force

Rollback Migrations:

This is one of the best feature of laravel’s migration. This feature can be used if we have messed up something in our last migration, we can rollback it using below command:

php artisan migrate:rollback

This command rolls back the last migrations, which may include multiple migration files.

We can rollback specific numbers of migrations by providing the –step option. Refer following command:

php artisan migrate:rollback --step=3

This will rollback the last three migrations. After this, you can open the related migration file, make changes as per your need and run php artisan migrate command again.

If you want to rollback all of your migrations up until now, you can do it using the reset option.

php artisan migrate:reset

Rollback & Migrate In Single Command:

Yes, we can rollback and migrate in a single command using migrate:refresh. This command will roll back all of your migrations and then execute the migrate command :

php artisan migrate:refresh

As same as, we can also rollback & re-migrate a limited number of migrations by providing the step option to the refresh command :

php artisan migrate:refresh --step=3

Drop All Tables & Migrate :

You can drop all tables from the database and then execute the migrate command:

php artisan migrate:fresh

Okay, you have created a table using migration. Now, this database is empty, we will need some data that we can use in our application, And we can’t manually add data in the database every time we change our migrations. Laravel provides data seesers that we can use for this purpose.

Creating Database Seeders

Laravel seeders is the simplest way to generate dummy data into a database. All seed classes are stored in the database/seeds directory. Once you create a seeder, all teammates can seed it to their local database. Let’s see how to create it.

To generate a seeder, we will use make:seeder artisan command :

php artisan make:seeder OurTableSeeder
Using the above command, laravel creates OurTableSeeder in the database/seeds directory. Now let’s modify it.

<?php

	use Illuminate\Database\Seeder;
	use Illuminate\Support\Facades\DB;
	class OurTableSeeder extends Seeder
	{
		/**
		* Run the database seeds.
		*
		* @return void
		*/
		public function run()
		{
			DB::table('users')->insert([
				'email_id' => str_random(10).'@gmail.com',
				'full_name' => str_random(7),
				'about' => str_random(10),
			]);
		}
}

As you can see in the above line of codes, we have run() method by default. This method is called when the db:seed artisan command is executed.

Using Factory :

Yes, we can use modal factories to create a large amount of database records. Refer following sample code:

/**
 * Run the database seeds.
 *
 * @return void
 */
public function run()
{
// create 100 users with just one line
	factory(App\User::class, 100)->create()->make());
}

Run Seeders :

After creating seeders, we need to regenerate Composer’s autoloader using the dump-autoload command:

composer dump-autoload

Now we may use the db:seed artisan command to seed our database. 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
php artisan db:seed --class=OurTableSeeder 

Or we can edit the DatabaseSeeder class to include our all seeders class.

<?php

use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;

class DatabaseSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $this->call([
            OurTableSeeder::class
        ]);
    }
}

You may also seed your database while migrating using the seed option with migrate:fresh command, which will drop all tables and generate all tables using migration and seed all tables with data.

php artisan migrate:fresh --seed

Sometimes, due to alteration or possibility of loss of any data, seed command will ask for confirmation for seeders to execute, But you can override this using force option, This will execute seeders without any prompt.

php artisan db:seed --force

So, Using migration and seeders in laravel, we can easily work with database structure and dummy data.

0 0 votes
Article Rating
guest
0 Comments
Inline Feedbacks
View all comments