How to Use Factory in Seeder Laravel?

By Hardik Savani April 16, 2024 Category : 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, laravel 8, laravel 9, laravel 10 and laravel 11 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 App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;

use Illuminate\Database\Eloquent\Model;

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 Database\Seeders;

use Illuminate\Database\Seeder;

use App\Models\Item;

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 Database\Factories;

use App\Models\Item;

use Illuminate\Database\Eloquent\Factories\Factory;

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:

I hope it can help you...

Shares