Support the ongoing development of Laravel.io →
posted 3 years ago
Last updated 2 years ago.
0

In Laravel 8, it's ridiculously simple and magical:

$numberOfProducts = 8;

return Category::factory()
    ->hasProducts($numberOfProducts)
    ->create();

There are quite a few more alternatives to create relationships. Pls check the docs for more.

I also suggest generate products this way:

class ProductFactory extends Factory
{
    public function definition()
    {
        return [
            'category_id' => function () {
                return Category::factory()->create()->id;
            }
        ];
    }
}
Last updated 3 years ago.
0

kevin, all that does is create 1 product , this is what worked for me instead

Product::factory() ->has(Category::factory())->count(10) ->create();

0

Great! Have you define the products relationship in the Category model:

class Category extends Model
{
    public function products()
    {
        return $this->hasMany(Product::class);
    }
}
0

yes i have , thanks :)

0

Sign in to participate in this thread!

Eventy

Your banner here too?

Sarmen B sarmenbj Joined 30 Mar 2021

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.