Laravel
Beginner
1 min read
Seeders, Factories, and Fake Data
Example
<?php
// database/factories/PostFactory.php
namespace Database\Factories;
use App\Models\User;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;
class PostFactory extends Factory
{
public function definition(): array
{
$title = $this->faker->sentence(6);
return [
'user_id' => User::factory(),
'title' => $title,
'slug' => Str::slug($title),
'body' => $this->faker->paragraphs(4, true),
'status' => $this->faker->randomElement(['draft', 'published']),
'published_at' => $this->faker->optional()->dateTimeThisYear(),
];
}
public function published(): static
{
return $this->state(fn(array $attrs) => [
'status' => 'published',
'published_at' => now()->subDays(rand(1, 30)),
]);
}
}
// database/seeders/PostSeeder.php
class PostSeeder extends Seeder
{
public function run(): void
{
\App\Models\Post::factory(50)->published()->create();
}
}
Related Resources
Laravel Reference
Complete tag & property list
Laravel How-To Guides
Step-by-step practical guides
Laravel Exercises
Practice what you've learned
More in Laravel