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

--

--

--

Freelancer Developer.

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Are you in love with Product Managment?

Libraries

KubeCon EU virtual 2020

The Power of a Single Plank

Building code from a Front-end point of view

FinBox CollectX — The Key to Smooth Collections

Trends of Developer community — A view using Data Science approach on Stack Overflow Data

fig. 1

LinkedList -A treasure hunt towards explanation. (Java)

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
Saurabh Mahajan

Saurabh Mahajan

Freelancer Developer.

More from Medium

Laravel & Angular-material: server side pagination (Part 2)

Using Database Transactions in Laravel

Laravel: How to retrieve model by Database field other than id

Granular permissions with Laravel APIs & React frontend