rai*_*son 3 uuid laravel laravel-seeding
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
]);
}
Run Code Online (Sandbox Code Playgroud)
I would like the UUID to be generated for each user in the database. So each row has a unique UUID.
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.
}
Run Code Online (Sandbox Code Playgroud)