coder81's avatar

Prevent update empty password

Where is the right place to put the check of an empty value? In the model, or in the controller? In my model I have this mutator to hash the password before save it in the database:

    public function setPasswordAttribute($password)
    {
        return $this->attributes['password'] = bcrypt($password);
    }

But I need to do this check in the controller to prevent update password with an empty value:

        if (trim($request->password) != '') {
           $user->password = $request->password;
        }

Where is the right place to put this check according to SOLID principles?

0 likes
10 replies
bobbybouwmann's avatar

Well a password is always required right? So in that case you would do that check in the validation of your form. In the case of Laravel a Request class. After that the logical place would be the controller in my opinion

1 like
coder81's avatar

Sorry, I not specified that this check is in the update, because the password is required in the create, but not in the update.

bobbybouwmann's avatar

You should check this in your controller and make sure that the password field isn't posted when it's empty for example

if ($request->get('password') == '') {
    $user->update($request->except('password'));
} else {
    $user->update($request->all());
}
2 likes
coder81's avatar

If all my fileds is required this is a bad solution?

$user->update(array_filter($request->all()));
bobbybouwmann's avatar

What is array_filter doing here?

Laravel models have a $fillable property which protects you to assigning field that you don't want to be assigned through a form.

coder81's avatar

array_filter remove all empty elements of an array, and becouse all my model attributes is required it works. Yes, I know and I use the $fillable property.

ruslansuhar's avatar

Another solution is to use the exclude_if validation rule to solve this:

'password' => 'sometimes|nullable|string|exclude_if:password,null',

So the $request->validated(); won't return the password field, when it's empty.

joelinman's avatar

@martinbean this thread appeared at the top of the 'Unsolved' Category for me, so i'm assuming it did for them too

1 like
ruslansuhar's avatar

@martinbean Found this post in Google results. Just thought someone would get here the same way and could use my solution.

Please or to participate in this conversation.