mercredi 22 juin 2016

Laravel 5: Password change only when password is changed

I am currently working on a user edit form on my Laravel app and it includes a password input. Currently each time I click on the update button it updates the password even without changing the current password. I would like have the password reset happen only when there is an input. Below is my code:

User Controller

public function update(Request $request, $id)
{
   //
    $user = User::findOrFail($id); 
    $user->name = $request->get('name'); 
    $user->email = $request->get('email'); 
    $user->password = $request->get('password');

    $this->validate($request, User::validationRules());

    $user->save(); 
    return redirect('/user');     
}

User.php (Model)

public static function validationRules( $attributes = null )
{
    $rules = [
        'name' => 'required|string|max:100',
        'email' => 'required|email' 
    ];

    // no list is provided
    if(!$attributes)
        return $rules;

    // a single attribute is provided
    if(!is_array($attributes))
        return [ $attributes => $rules[$attributes] ];

    // a list of attributes is provided
    $newRules = [];
    foreach ( $attributes as $attr )
        $newRules[$attr] = $rules[$attr];
    return $newRules;
}

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



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire