Laravel empty password hashed on user update

When I update my model bound form with

$user->update(Input::all())

      

My password field is re-hashed even when empty. I have set my User.php class to auto hash this field, but shouldn't I skip it since the field is empty?

+3


source to share


4 answers


You can use in this case:

Input::except('password')

      

so in your controller you can do it like this:

if (trim(Input::get('password')) == '') {
   $data = Input::except('password');
}
else {
   $data = Input::all();
}
$user->update($data);

      

However, you should consider other possible problems for this. In this case, if a user submits input with a name id

(and anyone can do it, even if you don't have such a field in your form), he can easily change other user / account passwords and destroy all your data.



You should use at User

least in your model:

protected $guarded = array('id');

      

to protect the user ID from being changed during bulk assignment , but there may be other fields that you would like to protect (you must list them in an array $guarded

.

For me, a much better option in this case is to use a standard custom update:

$user = User::find($id);

if (trim(Input::get('password')) != '') {
   $user->password = Hash::make(trim(Input::get('password')));
} 
$user->name = Input::get('name');
// and so on - this way you know what you are changing and you won't change something you don't want to change
$user->save();

      

+3


source


Just as Tom Bird commented, here is some sample code for example.

If you are using a type mutator in your model setPasswordAttribute()

, then you can do this:



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

      

This will prevent the new password from being hashed. This setPasswordAttribute () method is called a "mutator" and became available in Laravel 4.2 from what I see. http://laravel.com/docs/4.2/eloquent

+2


source


Since you sent all the input to the custom model, it is assumed that you want to update all fields, including the password, even if it is an empty string, possibly a hash of an empty string.

You need to check if the password is empty and if it is used Input::except('password')

+1


source


public function update($id)
{
    $register = Register::findOrFail($id);
    if (empty(Request::get('password'))) {
        $data = Request::except('password');
    } else {
        $data = Request::all();
    }
    $register->update($data);
    return redirect('register');
}

      

-1


source







All Articles