不能让Laravel注册表单使用散列存储密码


Can't get Laravel registration form to store passwords with a hash

Laravel存储了用户名和电子邮件,但是当我添加哈希函数时,没有为密码字段保存任何内容。控制器代码:

public function store()
{
    $data = Input::only(['username','email','password' => Hash::make('password')]);
    $newUser = User::create($data);
    if($newUser)
    {
        Auth::login($newUser);
        return Redirect::route('profile');
    }
    return Redirect::route('user.create')->withInput();
}

使用此代码,在注册新用户后,密码的数据库字段仅为空白。一旦我删除哈希函数,明文密码插入ok。密码需要在用户提交信息后以散列形式存储。当我用artisan播种数据库时,哈希函数工作得很好,但当我在控制器逻辑中使用它时就不行了。有人能帮忙吗?

EDIT: In User.php

protected $fillable = ['username','email','password'];

好的,除了你上面的代码不能工作之外,你的方法是错误的。

首先,你要做的方法是:

$input = Input::only(['username', 'email', 'password']);
$input['password'] = Hash::make($input['password']);

只设置值的方法不起作用,除此之外,您有Hash::make('password'),它每次都会对'password'进行哈希,而不是变量,而是单词。Input::only()接受一个字段名数组来返回,因此它使用数组的值,而不是键。数组['password' => Hash::make('password')]的值是password的哈希值,而不是password的哈希值。

最好的方法是这样的:

$input = Input::only(['username', 'email', 'password']);
$user = User::create($input);

然后,在您的User模型中,您有:

public function setPasswordAttribute($value)
{
    $this->attributes['password'] = Hash::make($value);
}

这意味着你不必为哈希而烦恼,并且可以相信模型会为你做这些。

另外,如果内存不够,Auth::login()接受一个整数,而不是一个模型,所以它将是Auth::login($newUser->id)登录刚刚注册的用户,尽管我强烈建议通过电子邮件进行某种验证/激活。