3

I have just added a UUID for my users table.

I want to update all the records with a UUID that is unique.

In my seeder I have the following code that generates a UUID and populates this new column in the database. However, the generated UUID is the same in each row.

public function run()
{
  DB::table('users')->update([
    'public_id' => Uuid::generate(4)->string
  ]);
}

I would like the UUID to be generated for each user in the database. So each row has a unique UUID.

Hat tip to this SO question for help so far.

The Laravel UUID Package I'm using.

SuperStar518
  • 2,814
  • 2
  • 20
  • 35
ejntaylor
  • 1,900
  • 1
  • 25
  • 43

1 Answers1

6

It is not working because it is taking only one generated uuid for all of the user data.

You need to loop through each model data and generate the unique uuid and save.

public function run(){
        $users = \App\User::get();

        try{
            DB::beginTransaction();
            foreach($users as $user){
                $user->public_id = Uuid::generate(4)->string;
                $user->save();  
            }
            DB::commit();
       }
       catch(Exception $e){  
           DB::rollback();
    }
   //if incase you get exception during database seeding.
}
Lizesh Shakya
  • 2,482
  • 2
  • 18
  • 42