I don't want to have dupliactes into my users table. This would be ok:
╔═══╦════════════╦═════════════╦═════════════╗
║ ║ firstname ║ lastname ║ dateOfBirth ║
╠═══╬════════════╬═════════════╬═════════════╣
║ 1 ║ John ║ Mat ║ 1999-12-01 ║
║ 2 ║ Dave ║ Bittner ║ 1950-06-02 ║
║ 3 ║ John ║ Mat ║ 1900-11-02 ║
╚═══╩════════════╩═════════════╩═════════════╝
In my Laravel application (UserController), I am checking if the user already exists by calling the firstOrCreate Method (creating a new user):
public function store(UserRequest $request) {
$user = User::firstOrCreate([
'firstname' => request('firstname'),
'lastname' => request('lastname'),
'dateOfBirth' => request('dateOfBirth'),
]);
if($user->wasRecentlyCreated) {
// new
}else {
// existing
}
return redirect('/users');
}
This worked pretty well. Now, I can create a similar user successful (like the entry with the id=3 in the example table above). If I edit the birthday from entry 3 into 1999-12-01, Laravel says it is OK, but it isn't (duplicate with id=1) !
I also want to check on update, if the entry already exists (duplicate check after every update). I am searching a updateIfNotDuplicate method or something like that (like the firstOrCreate for updates).
This is my update function in the UserController:
public function update(User $user, UserRequest $request) {
$user->update([
'firstname' => request('firstname'),
'lastname' => request('lastname'),
'dateOfBirth' => request('dateOfBirth'),
]);
return redirect('/users');
}
UserRequestobject, why not add auniqueconstraint to thedateOfBirthcolumn?