Last Updated: January 23, 2019
·
38.8K
· eedithz

Nice way to hash password in laravel when creating new user

Here is how usually a laravel programmer hash a password when creating a new user.

$user = new User;

$user->username = Input::get('username');

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

$user->save();

With Hash::make($pass), the password will be hashed to string like this:

$2y$08$d2srMhTuQ22nzuh.EEuwQ.QWNW5Svl.KLBqudXKPvFG/HHzE3C4VC</code>

However, you can simplify the code to be something like this:

$user = new User;

$user->username = Input::get('username');

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

$user->save()

In order to code above to be worked, you need to tell the User model to hash the password automatically by simply adding this method to your User model class:

public function setPasswordAttribute($pass){

$this->attributes['password'] = Hash::make($pass);

}

In laravel world, the method shown above is called mutator, If you want to know more about mutator in laravel. Simply check link below:

http://laravel.com/docs/eloquent#accessors-and-mutators

2 Responses
Add your response

I do it this way:

$data = Input::all();

$user->password = Hash::make($data['password']);

I don't know, i find it simpler that way

over 1 year ago ·

Hey, i think this should do the trick. https://gist.github.com/sarbull/08f23fbb96490402cefc

over 1 year ago ·