Search code examples
phplaravel-5laravel-seeding

Laravel Seeding not working


Consider the below code:

foreach ($departments as $department)
        {
            factory(App\User::class, 100)->create()
            ->each(function ($u) use($department)
            {

                $u->employee()->save(factory(App\Employee::class)->make([
                    'department' => $department,
                    'emp_id' => '',
                ]));

            });

        }

Now for emp_id I want to have incremental value from 1 to 100 for each iteration of the outer foreach loop.

Example:

1st iteration 100 users and 100 employees record should be created with emp_id 1 to 100 with department as 'abc'

2nd iteration again 100 users and 100 employees record should be created with emp_id 1 to 100 with department as 'xyz' and so on.

I tried to declare $i=1 before the factory and then increment $i withing each() but it did not work and gave duplicate key error.

Note that the unique constraint in my table for employee is department-emp_id


Solution

  • This is a tricky one. The value of your index variable is not updating because when you pass primitives to a function in the use clause, they are copied. Only objects are passed by reference by default.

    To get around this, you need to explicitely pass your index variable as reference by prepending an &:

    foreach ($departments as $department)
    {
        $i = 1;
        factory(App\User::class, 100)->create()
            ->each(function ($u) use ($department, &$i)
            {
                $u->employee()->save(factory(App\Employee::class)->make([
                    'department' => $department,
                    'emp_id' => $i++,
                ]));
            });
    }
    

    I hacked together a small example to show the difference over at 3v4l.