Laravel Database Seeders and Factories (Best Way to Seed Data)

Laravel Database Seeders and Factories

This article will focus on how you can seed the data to your database. Seeding the data means to insert some fake data or some mandatory data on the fresh migration or whatever the situation will be. Typical and most common example will be to add admin to your application to the users table.

You can read more about seeders here.

You can read more about seeders here.

You can read more posts, read from https://www.opensourcelisting.com/author/khayam/

Seeders

Seeder files are located in the Database directory where you have migrations, seeds and factories. On fresh installation of Laravel application there exists only one file in the seeds called DatabaseSeeder which is the base file to run other seeders and factories and looks like,

<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    /**
     * Seed the application's database.
     *
     * @return void
     */
    public function run()
    {
        // \App\Models\User::factory(10)->create();
    }
}

but creating a seperate seeder for each model where you want to seed by default data is always the best practice and will run that specific file from the main seeder file.

So you can create a seeder file by command

php artisan make:seeder UserSeeder

This command will create a seeder file called UserSeeder in the seeds directory inside database.

Let’s seed some users by writing the following code,

<?php

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


class UserSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        DB::table('users') -> insert(
            [
                'name' => 'Admin One',
                'email' => '[email protected]',
                'password' => Hash::make('password'), 

            ]
        );
        DB::table('users') -> insert(
            [
                'name' => 'Admin Two',
                'email' => '[email protected]',
                'password' => Hash::make('password')

            ]
        ); 
       

    }
}

And Call this seeder file in the main database seeder file as,

<?php

use Illuminate\Database\Seeder;

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

You can call as many seeder as you want.

Now we want to migrate our migration files in order to we have tables in database so will migrate the files and will provide the seed flag to dump the data that we created in the seeder file.

php artisan migrate --seed

This will create database tables and will dump the data.

Now that you want to make change in the application and want to remigrate then it will not affect the initial data that dumped for the admin.

If you want a fresh migration with the particular data then execute the following command.

php artisan migrate:fresh --seed

you can also run the seed command even without to migrate or to fresh migrate like,

php artisan db::seed

Factories

Seeders are convenient when you seed small amount of data to database but if you will have large amount of data to seed for example seeding 1000 fake users to the database then factories are the best way to handle this situation.

Actually factory is a rule for what field should have which values if you want the seed the data and using a library called faker which is really good to fake data for example if you need random name, random email etc. it will help you with that.

Factories are located in the factories directory inside database directory. By default there is one factory called UserFactory which comes with the installation of laravel and looks like this,

<?php

/** @var \Illuminate\Database\Eloquent\Factory $factory */

use App\User;
use Faker\Generator as Faker;
use Illuminate\Support\Str;

/*
|--------------------------------------------------------------------------
| Model Factories
|--------------------------------------------------------------------------
|
| This directory should contain each of the model factory definitions for
| your application. Factories provide a convenient way to generate new
| model instances for testing / seeding your application's database.
|
*/

$factory->define(User::class, function (Faker $faker) {
    return [
        'name' => $faker->name,
        'email' => $faker->unique()->safeEmail,
        'email_verified_at' => now(),
        'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password
        'remember_token' => Str::random(10),
    ];
});

In the UserSeeder file we use this factory or you can directly use in databaseSeeder like,

<?php

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


class UserSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        factory(App\User::class, 10000) -> create();     
    }
}

By running this seed file as db seed will creare 10000 fake users.

Factories are usually used for testing like unit testing or even continuous integration, so we need data for automated tests and factories are best way to fake data.

Previous Post
Next Post

Comments

Avatar for ecomi token
ecomi token

Reading your article helped me a lot and I agree with you. But I still have some doubts, can you clarify for me? I’ll keep an eye out for your answers.

Avatar for khayam khan
khayam khan

yes Sure.
Feel free to ask.

Leave a Reply