Home » Difference Between Factory And Seeders In Laravel

Difference Between Factory And Seeders In Laravel

Last updated on December 24, 2020 by

In many instances, Laravel developers get confused about the difference between Factory and Seeders because they look similar to use. Even many developers don’t know the actual use of Factory and Seeders.

In this guide, we will teach you the difference between Factory and Seeders in a very very short & simplest manner. Ready? Let’s go then.

Table of Contents
1. Why We Use Factory and Seeders?
2. What is Seeders?
3. How to Create Seeders?
4. When Should I Use Seeders?
5. What is Factory?
6. How to Create Factories?

Why We Use Factory and Seeders?

In very simplest word, Factory and Seeders both are used to generate Fake/Test data. That means you don’t need to feed the data manually again & again for testing your WEB/API application. We hope you get this. Let’s go ahead and understand each one.

01 SEEDERS

What is Seeders?

Seeder is a Class. Seeder is used to create Fake or Test data by using table name.

How to Create Seeders?

To create a seeder, we need to run an Artisan command make:seeder. Let’s do step by step.

  1. Go to CLI and run an Artisan command php artisan make:seeder UsersSeeder
  2. UserSeeder class has been created into database/seeds directory
  3. Now open the database/seeds/UsersSeeder.php file and adjust the run method to the following.
  4. Don’t forget to adjust all the namespaces as following too.
<?php

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

class UsersSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        DB::table('users')->insert(
            [
                'name' => Str::random(10),
                'email' => Str::random(10).'@gmail.com',
                'password' => Hash::make('password'),
            ],
            [
                'name' => Str::random(10),
                'email' => Str::random(10).'@gmail.com',
                'password' => Hash::make('password'),
            ],
        );
    }
}
  1. Now open the database/seeds/DatabaseSeeder.php file and adjust the run method to the following.
<?php

use Illuminate\Database\Seeder;

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

  1. Then go to the CLI and run an Artisan command php artisan db:seed. That’s it. You can go to the database and check your “users” table. You can see 2 records have been created. Great! You have done a good job so far. Let’s go ahead.

Did you notice that you need to write a very repetitive code in Seeders? To create more users you need to repeat more arrays. And even to seed other tables, you need to create more seeders class.

Do you think that is practical? In this situation, the Factory is very useful, but that we will see later. Let’s first complete the final bits of the seeder.

When Should I Use Seeders?

It is not meant that seeders are not useful. We have found lots of cases where seeders are very very useful as following.
1. When you have a predefined dataset like a large number of Questionnaires, Surveys, etc.
2. To create default users like Administrator.
3. Dictionaries, Medicines data, Tutorials, etc.

02 FACTORY

What is Factory?

Factory is a helper function. It is also a global object. The Factory is used to create Fake or Test data by using the Model.

It uses a Faker class to generate dummy data. Factory can also generate relationship data with the Model which seeder can’t do.

How to Create Factories?

To create a factory, we need to run an Artisan command make:factory. You can find out the default UserFactory example in database/factories directory. Let’s create the Factory step by step.

  1. Go to CLI and run an Artisan command php artisan make:factory PostFactory
  2. PostFactory file has been created into database/factories directory
  3. Now open the database/seeds/PostFactory.php file and adjust as the following.
  4. Don’t forget to adjust all the namespaces as following too.
<?php

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

use App\Post;
use Faker\Generator as Faker;

$factory->define(Post::class, function (Faker $faker) {
    return [
        'title' => $faker->sentence(5),
        'description' => $faker->text(),
        'user_id' => factory('App\User')->create()->id,
    ];
});

  1. Now open the database/seeds/DatabaseSeeder.php file and adjust the run method to the following.
<?php

use App\User;
use App\Post;
use Illuminate\Database\Seeder;

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

  1. Then go to the CLI and run an Artisan command php artisan db:seed. That’s it. You can go to the database and check your “users” & “posts” table. You can see 2 records have been created. Great! You have done a good job so far.

It is advisable to learn about Faker to understand different functions from here.

Additionally, read our guide:

  1. Specified Key Was Too Long Error In Laravel
  2. Run PHP Artisan Commands On Shared Hosting Servers
  3. How To Calculate Age From Birthdate
  4. Active Directory Using LDAP in PHP or Laravel
  5. How To Use The Laravel Soft Delete
  6. How To Add Laravel Next Prev Pagination
  7. cURL error 60: SSL certificate problem: unable to get local issuer certificate
  8. Difference between Events and Observers in Laravel
  9. Best Way to Remove Public from URL in Laravel
  10. Session Not Working In Laravel

That’s all from our end. We hope this article helped you to learn the difference between Seeder and Factory in a very simple and short way.

Please let us know in the comments if everything worked as expected, your issues, or any questions. If you think this article saved your time & money, please do comment, share, like & subscribe. Thank you for reading this post. Keep smiling 🙂 & Keep coding!

 
 

2 thoughts on “Difference Between Factory And Seeders In Laravel”

Leave a Comment