How can I prevent Laravel from validating certain columns when editing an existing user? I’m trying to update a guest’s information, but I want to ignore the phone and email fields if no changes have been made to the guest’s details. However, when creating a new guest, it should properly check for uniqueness. How can I achieve this? I’ve been struggling with this issue for a while.
Here are my form validation rules:
return [
'first_name' => 'required|string|max:255',
'last_name' => 'nullable|string|max:255',
'other_names' => 'nullable|string|max:255',
'city' => 'nullable|string|max:255',
'country' => 'nullable|string|max:255',
'email' => ['required_if:phone,null', Rule::unique('guests')->whereNot('email',null)->where('hotel_id',auth()->user()->hotel_id) ],
'phone' => ['required_if:email,null', Rule::unique('guests')->where('phone','!=', $request->phone)->where('hotel_id',auth()->user()->hotel_id) ],
'address' => 'nullable|string|max:255',
'other_phone' => 'nullable|numeric:11',
];
Any assistance would be greatly appreciated.
2
Answers
You can use the
Rule::unique()
method to ignore a certain ID during the validation. This is useful when updating a model and wanting to ignore the model itself.In the above code,
Rule::unique('guests')->ignore($guestId)
tells Laravel to enforce the uniqueness.Just compare the value to save with the value in the model attribute. E.g.: