Seeders populate your database with test data. Factories define how to generate fake model instances for testing and seeding.
php artisan make:factory PostFactory --model=Post
// database/factories/PostFactory.php
class PostFactory extends Factory
{
public function definition(): array
{
return [
'user_id' => User::factory(),
'title' => fake()->sentence(),
'slug' => fake()->unique()->slug(),
'body' => fake()->paragraphs(3, true),
'published' => fake()->boolean(70),
'published_at' => fake()->dateTimeThisYear(),
];
}
// Custom state
public function draft(): static
{
return $this->state(['published' => false, 'published_at' => null]);
}
}
php artisan make:seeder PostSeeder
class PostSeeder extends Seeder
{
public function run(): void
{
Post::factory(50)->create();
Post::factory(10)->draft()->create();
}
}
php artisan db:seed // Run DatabaseSeeder
php artisan db:seed --class=PostSeeder // Run specific seeder
php artisan migrate:fresh --seed // Migrate and seed
// Creates and persists to DB
$user = User::factory()->create();
$posts = Post::factory(3)->for($user)->create();
// Creates without persisting
$post = Post::factory()->make();