0

I was trying to create a seeder for Products table with two foreign keys (category_id and sub_category_id for categories and sub_categories tables respectively).

Category::all()->each(function ($category) {
        SubCategory::all()->each(function ($sub_category) {
            $faker = Faker::create();
            for($i = 0; $i < 3; $i++) {
                DB::table('products')->insert([
                    'product_name' => $faker->name,     
                    'product_description' =>  $faker->sentence,
                    'product_price' =>  rand(100, 1000),
                    'product_quantity' =>  rand(10,100),
                    'category_id' => $category->id,
                    'sub_category_id' =>  $sub_category->id,
                ]);
            }
        });
    });

Tried this but it's returning me an error of

Undefined variable: category

I can create seeder with only the sub_category but I needed to create with category as well. How am I supposed to do that?

MDB
  • 339
  • 4
  • 19
  • Create different seeder for all three tables. and then use [random order](https://stackoverflow.com/questions/13917558/laravel-eloquent-or-fluent-random-row) to fetch random category & random sub category & save that in product. – Bhaumik Pandhi Apr 21 '20 at 13:24

2 Answers2

3

As you know, you are passing an anonymous function to the each() method. Anonymous functions don't have access to the variables outside of their scope.

You must pass the $category variable to the SubCategory's each() method this way:

Category::all()->each(function ($category) {
    SubCategory::all()->each(function ($sub_category) use ($category) {
        // now you have access to the $category
    });
});

As you can see I'm passing it by use ($category) to the function.

Ali Tavafi
  • 443
  • 1
  • 10
  • 28
0

You are using a closure to go through each item in the SubCategory model. The initialisation of the $category variable is outside of the closure's scope. In order to access $category you need to make it available by using the use keyword:

SubCategory::all()->each(function ($sub_category) {...});

to

SubCategory::all()->each(function ($sub_category) use ($category) {...});
kidA
  • 1,379
  • 1
  • 9
  • 19