Search code examples
laravelmigrationfakerlaravel-seedinglaravel-factory

Create seeder for a table with two foreignkeys


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?


Solution

  • 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.