Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

mbpp's avatar
Level 3

Create Method on User Model (bcrypt)

After looking at the new laravel version 5.4 i notice when using "$user = User::create(request(['name', 'email','password']));" the password isnt automatically bcrypt the password, is it me, or isnt by defaul bcrypt by default? I dont remember, but isnt supposed the method "create" already do this?

0 likes
4 replies
DarkRoast's avatar

It's not automatically encrypted but you can add a mutator to your User model to do that:

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

@mbpp I’d avoid adding a mutator to the password attribute, in case you have a hash you want to set directly. If you try and set the password hash using $user->password = $hash, then that hash is going to get re-hashed.

Instead, just add another method:

public function setPassword($password)
{
    $this->password = bcrypt($password);

    return $this;
}

You now have the ability to set a password to an existing hash:

$hash = bcrypt('string');

$user->password = $hash;

Or set a plain text password and have the model hash it:

$user->setPassword('secret');

I stay away from transforming values from one representation to another in mutators as it can lead to unexpected behaviour in my applications if I think I’m setting it to one value, but then another value appears in its place, i.e. in the database.

Mahen's avatar

To avoid repeated calls to setPasswordAttribute i used

public function setPasswordAttribute($password)
{
    if(Hash::needsRehash($password)) 
        $password = Hash::make($password);

    $this->attributes['password'] = $password;
}
3 likes

Please or to participate in this conversation.