ifmvxa
Last Updated: February 25, 2016
·
18.39K
· eedithz
0bb79048bb1a2eccfe3953fff074ad80

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

Say Thanks
Respond

2 Responses
Add your response

13573
F99c0d5767fc68412014ae43799dc267

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 ·
17767
0bfcd39eb1ec753fcc00f2e88bbea6bd

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

over 1 year ago ·