Support the ongoing development of Laravel.io →
posted 4 years ago

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 ];

Last updated 3 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 4 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.

© 2025 Laravel.io - All rights reserved.