Raj
Raj

Reputation: 2028

How to increment a column values by 1 while creating factory in laravel 5.6?

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 ?

Upvotes: 0

Views: 961

Answers (1)

WallSky Blue
WallSky Blue

Reputation: 210

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

Upvotes: 1

Related Questions