Laravel Model Factories

php artisan make:factory PostFactory -m Post
php artisan make:modle Post -mf
    public function definition()
{
return [
//
'comment' => $this->faker->paragraph(),
'approved' => $this->faker->boolean(80),
];
}
App\Models\Post::factory()->create()
App\Models\Post::factory()->make()
App\Models\Post::factory()->count(5)->create()
App\Models\Post::factory()->create(['comment' => 'Our Specific Comment']);
App\Models\Post::factory()->count(5)->create(['approved' => true]);
    public function approved_posts() 
{
return $this->state(function (array $attributes) {
return [
'approved' => true,
];
});
}
App\Models\Post::factory()->count(5)->approved_posts()->create();
Post::factory()
->count(10)
->state(new Sequence(
['approved' => true],
['approved' => false],
))
->create();
Post::factory()
->count(10)
->state(new Sequence(
['approved' => true],
['approved' => true],
['approved' => false],
))
->create();
return [
//
'user_id' => User::factory(),
'comment' => $this->faker->paragraph(),
'approved' => $this->faker->boolean(80),
];
App\Models\Post::factory()->create()
App\Models\Post::factory()->count(5)->create()
$user = User::factory()->create();
$posts = Post::factory()
->count(5)
->create(['user_id' => $user->id]);
$user = User::factory()->create();
$posts = Post::factory()
->count(5)
->for($user)
->create();
User::factory()
->has(Post::factory()->count(5))
->create();
User::factory()
->has(Post::factory()->approved_posts()->count(5))
->create();
$user = User::factory()
->hasPosts(3)
->create();
    public function posts() 
{
return $this->hasMany(\App\Models\Post::class);
}
User::factory()
->count(50)
->has(
Post::factory()
->has(Comment::factory()->count(10))
->count(5)
)
->create();
php artisan migrate:fresh --seed

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store