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;
}
];
}
}
kevin, all that does is create 1 product , this is what worked for me instead
Product::factory() ->has(Category::factory())->count(10) ->create();
Great! Have you define the products
relationship in the Category
model:
class Category extends Model
{
public function products()
{
return $this->hasMany(Product::class);
}
}
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community