Laravel 如何自动插入随机密码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/44569845/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel how to insert random password automatically
提问by Namika.L
With Laravel 5.4, I have users table
使用 Laravel 5.4,我有用户表
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.
然后当我插入新的用户数据时,我想自动生成随机密码(如 9c41Mr2)。
For example, once I insert one data:
例如,一旦我插入一个数据:
$data = [
'email' => '[email protected]',
];
DB::table('users')->insert($data);
I want new row in MySQL like this:
我想要像这样在 MySQL 中的新行:
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.
所以,有人能告诉我 Laravel 的最佳方式吗?谢谢。
PS: don't worry about password hashing, I made my question simple.
PS:不要担心密码散列,我把我的问题简单化了。
回答by Mathieu Ferre
In your User model :
在您的用户模型中:
public function setpasswordAttribute($value)
{
$this->attributes['password'] = bcrypt($value ?: str_random(10));
}
回答by Mathieu Ferre
Use a mutator method to set the password. Override the method by adding:
使用 mutator 方法设置密码。通过添加以下内容来覆盖该方法:
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
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.
设置属性时根本不需要使用 $value 参数。
回答by Gabriel Caruso
回答by raison
@Mathieu answer needs amending in light of some new changes to Laravel. Now generate the password using the following facades:
@Mathieu 的回答需要根据 Laravel 的一些新变化进行修改。现在使用以下外观生成密码:
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));
}