My app's user table cannot use a unique column. So I've done this with the Laravel validation. The problem with this is that the "race condition" problem sometimes occurs when registering a user.
I have tried several ways to fix the problem
I used firstOrCreate and now firstOrNew but the problem didn't fix.
Although I have checked the record for non-duplicate records in the previous lines, I also checked the record's duplication status when adding records to the database, but the problem was not fixed.
<?php
class RegisterController extends Controller
{
protected function validator(array $data)
{
return Validator::make($data, [
'phone' => ['required', 'digits:11', 'unique:users,phone,null,id,deleted_at,NULL', phoneRegExValidateRule()],
// other fields ...
]);
}
protected function create(array $data)
{
$user = User::firstOrNew([
'phone' => $data['phone'],
]);
if ($user->exists) {
flash()->error('error', 'duplicate user');
return redirect()->route('home');
} else {
$user->fill([
// fields ...
]);
$user->save();
}
$user->meta()->create([
// fields ...
]);
return $user;
}
}
Since the "race condition" problem occurs at the last moment and when the record is inserted into the database, it seems that I should use table locking. But I don't know what happens to other parts of the program that use this table when locked. I also don't know how to write this code