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.
nullable
to yourpassword
rule? I.E.:'password' => 'nullable|same:...'
. Thepassword
field should be blank if the Admin doesn't fill it out, andnullable
, as the first rule, should prevent the other rules from being checked. – Tim Lewis