0
votes

I'm having a admin dashboard in my laravel application

From the dashboard Admin can edit the user profile contents.

Here is my current usercontroller (only the update function included)

public function update(Request $request, $id)
{
    $this->validate($request, [
        'name' => ['required', 'alpha','min:2', 'max:255'],
        'last_name' => ['required', 'alpha','min:2', 'max:255'],
        'email' => ['required','email', 'max:255', 'unique:users,email,'.$id],
        'password' => ['same:confirm-password','regex:/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{12,}$/'],
        'mobile'=>['required', 'regex:/^\+[0-9]?()[0-9](\s|\S)(\d[0-9]{9})$/','numeric','min:9'],
        'username'=>['required', 'string', 'min:4', 'max:10', 'unique:users,username,'.$id],   
        'roles'=>['required'],
        //'user_roles'=>['required'],
    ]);

    $input = $request->all();
    if(!empty($input['password'])){ 
        $input['password'] = Hash::make($input['password']);
    }else{
        $input = array_except($input,array('password'));    
    }

    $user = User::find($id);
    $user->update($input);
    DB::table('model_has_roles')->where('model_id',$id)->delete();

    $user->assignRole($request->input('roles'));

    if($input['roles']=='customer'){
        return redirect()->route('customers.index')
                    ->with('success','Customer has been updated successfully');
    }
    else{
        return redirect()->route('users.index')
                    ->with('success','User has been updated successfully');
    }
}

Now my problem is,

When ever admin updates an user without changing the password fields, the password fields get validated and throw me a regex error related to the password...

How can I avoid that issue and validate password field only if they are being changed.

1
@DigitalDrifter I have validated the password field with same:confirm-password, so do I need to validate the confirm-password field again?Volka Dimitrev
but in the default laravel auth used registration, only the password filed is validated right?Volka Dimitrev
Does it work if you add nullable to your password rule? I.E.: 'password' => 'nullable|same:...'. The password field should be blank if the Admin doesn't fill it out, and nullable, as the first rule, should prevent the other rules from being checked.Tim Lewis

1 Answers

1
votes

With your current validation rules password field will always be checked with the regex. Adding nullable rule in first position of your password validation rules could help you solving the issue.