0

I want to generate 1000 users and then generate another 1000 record for the NewUser table which is working properly but the registration_no field is breaking the unique key constraint.

So i guess its always storing value 1 in registration field.

        $i = 1;

        factory(App\User::class, 1000)->states('newuser')->create()
        ->each(function ($u) use($i)
        {

            $u->newuser()->save(factory(App\NewUser::class)->make([
                'registration_no' => $i,
            ]));

            $i++;

        })

So how do I actually increment the field by 1 everytime new user is created ?

Raj
  • 1,928
  • 3
  • 29
  • 53
  • Just curious, but why do you want a registration_no that increments by 1? Wouldn't this be a duplicate field when you already have an auto-increment id? – Devon Bessemer Jun 07 '18 at 13:38
  • well this is just an example. In real application the scenario is different. The main part is how do I generate 1000 users with one of the field incrementing by 1 everytime. – Raj Jun 07 '18 at 13:39
  • I would expect your code to work, although, I'd probably just use $i++ in the make() instead of a $i++ afterwards. I'm not sure I understand the NewUser relationship you have there but $i should be incrementing. – Devon Bessemer Jun 07 '18 at 13:41
  • Perhaps you already have a few records in your newuser table? – Devon Bessemer Jun 07 '18 at 13:44
  • It gives error: syntax error, unexpected '$i' (T_VARIABLE), expecting ',' or ')' – Raj Jun 07 '18 at 13:47
  • The call back in the `each()` method has a second parameter `$key` which should be the index of the current looped item and it should work for you. – thefallen Jun 07 '18 at 14:32
  • I tried using $key but it does not work. It says undefined variable key – Raj Jun 07 '18 at 14:46

1 Answers1

1

to increase $i value for each new user you must use use(&$i) to pass reference instead of use($i) which supply 1 to closure on every run

WallSky Blue
  • 211
  • 2
  • 7