0

When calling User->update($data) with mass-assignment, is it possible to only set the users password if one is passed in?

View:

<form>
    <input type="text" name="name">
    <input type="text" name="email">
    <input type="password" name="password">
    <input type="submit">
</form>

Model:

<?php
class User extends Eloquent {            

    public static $rules = [
        'name' => 'required:max:32',
        'email' => 'required|max:128'
        'password' => 'min:8|max:128'
    ];

    // Allow mass-assignment for:
    protected $fillable = ['name', 'email', 'password'];

    // The attributes excluded from the model's JSON form.         
    protected $hidden = ['password', 'remember_token'];

}

Controller:

class UsersController extends BaseController {

    public function update($id)
    {
        $user = User::findOrFail($id);    
        $validator = Validator::make($data = Input::all(), User::$rules);

        if ($validator->fails())
            return Redirect::back()->withErrors($validator)->withInput();

        $user->update($data); // How do I only update password if password was passed in?
    }
}
1
  • $user->password(Input::get('password')); $user->save();
    – Ohgodwhy
    Sep 29, 2014 at 18:43

1 Answer 1

1

You should use:

$user->password = Hash::make(Input::get('password')); 

$user->save();

instead of:

$user->update($data);

to update only user password.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.