Ad

Laravel: Validation Alpha And Regex Pattern On Update

Hello all this is my update controller for an user. I want to know how can I apply these laravel validation rules ONLY to updated fields. Currently when I update only the first name, mobile number also get validated. My name fields are alpha validated and phone number is validated via regex.

public function update(Request $request, User $setting)
    {
         request()->validate([
            'name' => ['required', 'alpha','min:2', 'max:255'],
            'last_name' => ['required', 'alpha','min:2', 'max:255'],
            'mobile'=>['required', 'string','regex:/\+(9[976]\d|8[987530]\d|6[987]\d|5[90]\d|42\d|3[875]\d|
            2[98654321]\d|9[8543210]|8[6421]|6[6543210]|5[87654321]|
            4[987654310]|3[9643210]|2[70]|7|1)\d{1,14}$/'],
            'email' => ['required', 'string', 'email', 'max:255', 'unique:users,email,'.$setting->id.''],
        ]);

        $setting->update($request->all());


                        return Redirect::back()->with('success','User updated successfully');                
    }

I able to handle the email(unique) field, but not the others.

Ad

Answer

Considering the small chat we had in the comments, what you must do is to first get the model from the database and to diff the request with the model's attributes. Then you can keep the validation rules for the changed attributes only.

public function update(int $id, Request $request, User $userRepository)
{    
     $user = $userRepository->find($id);

     $changedAttributes = array_diff($request->all(), $user->getAttributes());

     $validationRules = array_intersect_key([
        'name'      => ['required', 'alpha','min:2', 'max:255'],
        'last_name' => ['required', 'alpha','min:2', 'max:255'],
        'mobile'    => ['required', 'string', 'regex:/\+(9[976]\d|8[987530]\d|6[987]\d|5[90]\d|42\d|3[875]\d|
        2[98654321]\d|9[8543210]|8[6421]|6[6543210]|5[87654321]|
        4[987654310]|3[9643210]|2[70]|7|1)\d{1,14}$/'],
        'email'     => ['required', 'string', 'email', 'max:255', 'unique:users,email,'.$setting->id.''],
    ], $changedAttributes);

    $this->validate($request, $validationRules);

    $user->update($changedAttributes);

    return Redirect::back()->with('success','User updated successfully');                
}
Ad
source: stackoverflow.com
Ad