Today's tutorial, you will learn how to create dummy data in database using Laravel Factory and Seed the database by using Database Seeder.

Generate model factory

Firstly, you need to generate model factory. To generate model factory, run below command in your terminal:
1
php artisan make:factory UserFactory --model=User

This will create a new file called UserFactory.php in database/factories folder.

Now we need to add fake data for each column in our model. For example, if we have a column called name, we need to add fake data for that column in our factory. Paste the below code in our factory file:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
<?php

namespace Database\Factories;

use App\Models\User;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Hash;
use Illuminate\Database\Eloquent\Factories\Factory;

class UserFactory extends Factory
{
/**
* The name of the factory's corresponding model.
*
* @var string
*/
protected $model = User::class;

/**
* Define the model's default state.
*
* @return array
*/
public function definition()
{
return [
'name' => $this->faker->name(),
'email' => $this->faker->unique()->safeEmail(),
'email_verified_at' => now(),
'password' => Hash::make('password'),
'remember_token' => Str::random(10),
];
}
}

Create User Seeder

Now, we need to create a seeder For UserTable by running command below:
1
php artisan make:seed UserTableSeeder

This will create a new file called UserTableSeeder.php in database/seeders folder.

Next Update the run function of seeder file. Paste the below code in the run function:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<?php

namespace Database\Seeders;

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

class UserTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
User::factory()->count(50)->create();
}
}

Seed the Data

Now Run the command below to seed the data:
1
php artisan db:seed --class=UserTableSeeder

Conclusion

In this tutorial, we learned how to create dummy data in database using Laravel Factory. If you have any issue regarding this tutorial, mention your issue in comment section or reach me through my E-mail.

Happy Coding