How to Use Factory in Seeder Laravel?
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 and laravel 9 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.
class Item extends Model
protected $fillable = [
we need to create add seeder for item.
Create Seeder with bellow command
php artisan make:seeder ItemSeeder
class ItemSeeder extends Seeder
* Run the database seeds.
* @return void
public function run()
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
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()
'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...
We are Recommending you
- Laravel US State Seeder Example
- Laravel Seeder from CSV File Example
- How to Run Specific Seeder in Laravel?
- How to Create Seeder with JSON data in Laravel?
- How to Run Migration and Seeder on Laravel Vapor?
- Laravel Import Large SQL File using Seeder Example
- How to use Google Charts in Laravel 8?
- Laravel 8 Cron Job Task Scheduling Tutorial
- Laravel 8 Database Seeder Tutorial Example
- Laravel 8 Auth with Livewire Jetstream Tutorial
- Laravel 7 Database Seeder Example
- How to Create Database Seeder in Laravel?