Laravel update password only if it is set

Viewed 7476

I am working on a laravel project with user login. The admin can create new users and edit existing users. I have got a password and a passwordConfirm field in the update-user-form. If the admin puts a new password in the form, it should check for validation and update the record in the db. If not, it shouldn't change the password (keep old one), but update the other user data (like the firstname).

If I try to send the form with an empty password and passwordConfirm field, it doesn't validate. I got a validation error, that the password must be a string and at least 6 characters long, but I don't know why. It seems like the first line of my update function will be ignored.

UserController.php

public function update(User $user, UserRequest $request) {

    $data = $request->has('password') ? $request->all() : $request->except(['password', 'passwordConfirm']);

    $user->update($data);

    return redirect('/users');
}

UserRequest.php

public function rules() {
    return [
        'firstname' => 'required|string|max:255',
        'lastname' => 'required|string|max:255',
        'email' => 'required|string|email|max:255',
        'password' => 'string|min:6',
        'passwordConfirm' => 'required_with:password|same:password',
    ];
}
4 Answers

Maybe you should try the following:

// ... more code

// Removes password field if it's null
if (!$request->password) {
    unset($request['password']);
}

 $request->validate([
    // ... other fields,
    'password' => 'sometimes|min:6'
    // ... other fields,
]);

// ... more code

you should replace "has" with "filled" in your code

$data = $request->filled('password') ? $request->all() : $request->except(['password', 'passwordConfirm']);

and actually it's better if you use the expression like this

    $request->request->remove('password_confirmation');
    ( ! $request->filled('password') ) ? $request->request->remove('password'):"";
    ( $request->has('password') ) ? $request->merge([ 'password' => Hash::make($request->post()['password']) ]):"";
    //then you can use 
    $user->update($request->all());

Even better, however, you have to use separate request classes for create and update "php artisan make:request" for ex: UserUpdateRequest.php and UserCreateRequest.php

for UserCreateRequest your rule is

'password' => 'required|confirmed|min:6',

for UserUpdateRequest your rule is

'password' => 'sometimes|nullable|confirmed|min:6',

and your controller head add this line

use App\Http\Requests\UserCreateRequest;
use App\Http\Requests\UserUpdateRequest;

and your update method must change

public function update(UserUpdateRequest $request, $id)
    {
     //
}
Related