How to Use Factory in Seeder Laravel?

Hello,

In this example, i will show you laravel seeder factory example. We will look at example of laravel seeder with factory. you will learn how to use factory in seeder laravel. step by step explain laravel factory seeder example.

Sometime we can create factory for generate face records for testing or anything. But in server it’s not possible direct run tinker command and each time. so we can create seeder for it and just run that seeder for generating fake records.

Here, we will create Item factory class and call in ItemSeeder to creating records. this example you can use in laravel 6, laravel 7 and laravel 8 version.

Let’s see bellow simple example:

Create Item Model

First let’s create item model as like bellow, i am not going to create migration and all, But just created model code here.

app/Models/Item.php

<?php

namespace AppModels;

use IlluminateDatabaseEloquentFactoriesHasFactory;

use IlluminateDatabaseEloquentModel;

class Item extends Model

{

use HasFactory;

protected $fillable = [

'title', 'body'

];

}

Create Seeder

we need to create add seeder for item.

Create Seeder with bellow command

php artisan make:seeder ItemSeeder

database/seeders/ItemSeeder.php

<?php

namespace DatabaseSeeders;

use IlluminateDatabaseSeeder;

use AppModelsItem;

class ItemSeeder extends Seeder

{

/**

* Run the database seeds.

*

* @return void

*/

public function run()

{

Item::factory()->count(5)->create();

}

}

Create Factory Class

we need to create create factory class with following command.

Create factory with bellow command

php artisan make:factory ItemFactory --model=Item

database/factories/ItemSeeder.php

<?php

namespace DatabaseFactories;

use AppModelsItem;

use IlluminateDatabaseEloquentFactoriesFactory;

class ItemFactory extends Factory

{

/**

* The name of the factory's corresponding model.

*

* @var string

*/

protected $model = Item::class;

/**

* Define the model's default state.

*

* @return array

*/

public function definition()

{

return [

'title' => $this->faker->title,

'body' => $this->faker->text,

];

}

}

Now we are ready to run seeder. let’s run seeder:

php artisan db:seed --class=ItemSeeder

Now you can see records in table:

How to Use Factory in Seeder Laravel?

I hope it can help you…

Leave a Comment