superjesus
superjesus

Reputation: 39

Not inserting data into DB as it should

I have this piece of code inside my UserController.

public function update(Request $r, User $user)
{
    $unEncryptedPassword = $r->password;
    $encryptedPassword = bcrypt($unEncryptedPassword);

    $r->password = $encryptedPassword;

    $user->update($r->all());

    return redirect('/users')->with('update', '');
}

I intend to encrypt the password and then insert the encrypted password into the database. Just before $user->update($r->all()); I checked doing an echo of the encrypted password, and indeed it is as it should. The problem is that when I submit that form, it inserts the unencrypted password and I don't know why.

Upvotes: 0

Views: 38

Answers (2)

namelivia
namelivia

Reputation: 2735

Try adding this mutator to the User model.

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

And then just pass the password in plaintext to the user model.

Upvotes: 1

Sergey Bogdanov
Sergey Bogdanov

Reputation: 671

Try this instead of modifying request:

public function update(Request $r, User $user)
    {
        $unEncryptedPassword = $r->password;
        $encryptedPassword = bcrypt($unEncryptedPassword);
        $requestData = $r->all();

        $requestData['password'] = $encryptedPassword;

        $user->update($requestData);
        return redirect('/users')->with('update', '');
    }

Upvotes: 2

Related Questions