I have two factories one for categories and another for products. When i run the factory i want to create x number of products for 1 category. how would i write the code to product this?
the definition for the categories is written as this:
return [ 'name' => $this->faker->word, 'slug' => Str::slug($this->faker->unique()->word, '-'), ];
and the definition for the product is written as such:
return [ 'category_id' => 1, //instead of 1 the category id used i want to be random 'name' => $this->faker->word, 'slug' => Str::slug($this->faker->unique()->word, '-'), 'description' => $this->faker->paragraph, 'price' => $this->faker->randomFloat(2, 0, 10000), 'is_visible' => 1, 'is_featured' => 1 ];
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