1. Create a factory
Step 1: Generate factory
Execute the following command to create a factory for your model:
php artisan make:factory ModelNameFactory --model=ModelName
example:
php artisan make:factory DepartmentFactory --model=Department
This will create a file in database/factories/DepartmentFactory.php
.
Step 2: Define the factory
Open the factory file and define the data structure. Use real data for better testing.
namespace Database\Factories;
use App\Models\Department;
use Illuminate\Database\Eloquent\Factories\Factory;
class DepartmentFactory extends Factory
{
protected $model = Department::class;
public function definition()
{
return [
'name' => $this->faker->word, // Generates a random department name
'description' => $this->faker->sentence, // Short description
'created_at' => now(),
'updated_at' => now(),
];
}
}
2. Build the Seeder
Step 1: Generate the Seeder
Execute the following command to create the seeder:
php artisan make:seeder SeederName
example:
php artisan make:seeder DepartmentSeeder
This will create a file database/seeders/DepartmentSeeder.php
.
Step 2: Define the Seeder
In a Seeder archive, use factories to generate records.
namespace Database\Seeders;
use App\Models\Department;
use Illuminate\Database\Seeder;
class DepartmentSeeder extends Seeder
{
public function run()
{
// Generate 10 departments
Department::factory(10)->create();
}
}
3. Register a seeder
Step 1: Add Seeder to DatabaseSeeder
exist database/seeders/DatabaseSeeder.php
call DepartmentSeeder
:
namespace Database\Seeders;
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
public function run()
{
$this->call([
DepartmentSeeder::class,
]);
}
}
4. Run the planter
Execute the following command to seed the database:
php artisan db:seed
To run a specific seeder:
php artisan db:seed --class=DepartmentSeeder
5. Professional Practice
-
Use relationship in factory
If your model has relations, define them in the factory:
'user_id' => User::factory(), // Generates a user and assigns it to this model
-
Use custom status
Establish states for specific variants of the model:
public function admin()
{
return $this->state([
'role' => 'admin',
]);
}
Use it in a planter:
Department::factory()->admin()->create();
-
organizational sower
For larger projects, organize planters into modules:
database/
└── seeders/
├── Admin/
│ ├── UserSeeder.php
│ └── RoleSeeder.php
├── Product/
│ └── ProductSeeder.php
└── DepartmentSeeder.php
-
Factory test
Use factories in tests to generate test data:
$department = Department::factory()->create();
$this->assertDatabaseHas('departments', ['id' => $department->id]);
-
clear and seed
For a new test, execute:
php artisan migrate:fresh --seed
6. Usage examples
if you have a Department
Model you can now generate:
Department::factory()->count(10)->create();
Department::factory()->create([
'name' => 'Human Resources',
]);