When updating a specific user, I want to run unique validation for the 'username' and 'studentNumber' fields, but only for other users and not for the same user being updated because its already owned by them. If I use unique:users only, it will cause errors when updating because it will run the validation against the user themselves. Instead, I used Rule::unique('users')->ignore($user->id) to ignore the user being updated, but I need to pass the id of the user being updated to the Form Request. How do I accomplish this?
UserController.php
public function update(UpdateUserRequest $request, string $id)
{
try{
DB::table('users')->where('id',$id)->update($request->validated());
}catch(Exception $ex){
return response()->json(['message' => $ex->getMessage()], 409);
}
}
UpdateUserRequest.php
public function rules(): array
{
return [
'username' => [ Rule::unique('users')->ignore($user->id), 'string', 'max:255'],
'studentNumber' => [ Rule::unique('users')->ignore($user->id), 'string'],
];
}
Why don't you just validate first and then try the update?
you can use one of this two examples: