Reputation: 53
With Laravel 5.4, I have users table
Users table:
- id
- email
- password
- created_at
- updated_at
then when I insert new user data, I want to generate random password (like 9c41Mr2) automatically.
For example, once I insert one data:
$data = [
'email' => '[email protected]',
];
DB::table('users')->insert($data);
I want new row in MySQL like this:
id: 1 (generated by autoincrement)
email: [email protected]
password: 9c41Mr2 (wow! automatic!)
created_at: 2017-06-14 01:00:00
updated_at: 2017-06-14 01:00:00
so, could anyone tell me the best way in Laravel? Thanks.
PS: don't worry about password hashing, I made my question simple.
Upvotes: 5
Views: 33042
Reputation: 4412
In your User model :
public function setpasswordAttribute($value)
{
$this->attributes['password'] = Hash::make(Str::random(10));
}
Upvotes: 10
Reputation: 3575
All the other answers require that the password mutator be called explicitly (by either passing an empty password in the model attributes or by calling $user->password = '';
This would fail to insert if password
wasn't in the attributes list, this is the needed code for it to be generated if password
isn't filled
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
class User extends Model {
protected $fillable = [
//...
'password',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function save( array $options = [] ) {
if ( ! $this->exists && empty( $this->getAttribute( 'password' ) ) ) {
$this->password = Str::random( 16 );
}
return parent::save( $options );
}
public function setPasswordAttribute( $value ) {
if ( ! empty( $value ) ) {
$this->attributes['password'] = Hash::make( $value );
}
}
}
Upvotes: 1
Reputation: 2101
@Mathieu answer needs amending in light of some new changes to Laravel. Now generate the password using the following facades:
Hash::make(Str::random(10))
eg.
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
public function setpasswordAttribute($value)
{
$this->attributes['password'] = Hash::make(Str::random(10));
}
Upvotes: 13
Reputation: 869
In simple case, just use a Mutator
for your password, but, if your application grows up, it's considered to use Observers
Upvotes: 0
Reputation:
Use a mutator method to set the password. Override the method by adding:
public function setPasswordAttribute($value)
{
$this->attributes['password'] = 'some random password generator';
}
see the documentation here:
https://laravel.com/docs/5.4/eloquent-mutators#defining-a-mutator
You don't need to use the $value parameter at all when setting the attribute.
Upvotes: 1