skip to Main Content

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


  1. 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.

    use IlluminateValidationRule;
    
    // Assuming $guest is the guest being updated
    $guestId = $guest->id;
    
    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')->ignore($guestId)->where(function ($query) use ($request) {
                return $query->where('hotel_id', auth()->user()->hotel_id);
            }),
        ],
        'phone' => [
            'required_if:email,null', 
            Rule::unique('guests')->ignore($guestId)->where(function ($query) use ($request) {
                return $query->where('hotel_id', auth()->user()->hotel_id);
            }),
        ],
        'address' => 'nullable|string|max:255', 
        'other_phone' => 'nullable|numeric:11',    
    ];
    

    In the above code, Rule::unique('guests')->ignore($guestId) tells Laravel to enforce the uniqueness.

    Login or Signup to reply.
  2. Just compare the value to save with the value in the model attribute. E.g.:

    $guest = Guest::firstOrNew(/* ... */);
    $new = !$guest->exists;
    
    return [
        ...
        'email' => $new || $guest->email !== $request->email ? [/* validation rules */] : [],
        ...
    ];
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search