我使用Laravel 9进行验证表单注册,现在我想将正确的数据添加到数据库。这是我在controller
中的代码public function store(RegistrationRequest $request)
{
return redirect(
route(
'index.store',
['registration' => User::create($request->validated())]
)
);
}
但我的问题是,我想插入到数据库哈希密码。在模型中,我有哈希密码的函数,但我不知道如何插入数据库。
class User extends Model
{
use HasFactory;
protected $fillable = [
'login', 'password', 'email'
];
public function opinions()
{
return $this->hasMany(Opinion::class);
}
public function setPassword($value)
{
$this->attributes['password'] = bcrypt($value);
}
}
如果有人能帮我解决这个问题,我将不胜感激。
由于您使用的是laravel 9,因此您有两个选项来存储散列密码。
protected function password(): Attribute
{
return Attribute::make(
set: fn($value) => bcrypt($value),
);
}
裁判:defining-a-mutator
或更旧的方式是
public function setPasswordAttribute($value)
{
$this->attributes['password'] = bcrypt($value);
}
Ref: definitions A Mutator