无法使用Laravel注册表来存储带有哈希的密码

use*_*043 3 php hash password-protection laravel laravel-4

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();
}
Run Code Online (Sandbox Code Playgroud)

使用此代码,在注册新用户后,密码的数据库字段将保留为空白.删除哈希函数后,明文密码插入即可.用户提交信息后,密码需要以散列形式存储.当我用工匠种子数据库时,哈希函数工作正常,但是当我在控制器逻辑中使用它时.有人可以帮忙吗?

编辑:在User.php

protected $fillable = ['username','email','password'];
Run Code Online (Sandbox Code Playgroud)

oll*_*ead 9

好的,除了你上面的代码不起作用之外,你会以错误的方式解决这个问题.

首先,您尝试的方法是:

$input = Input::only(['username', 'email', 'password']);
$input['password'] = Hash::make($input['password']);
Run Code Online (Sandbox Code Playgroud)

你设置值的方法不起作用,除此之外,你Hash::make('password')每次都会产生一个'密码'的哈希,而不是变量,而是单词.Input::only()接受要返回的字段名称数组,因此它使用数组的值,而不是键.该数组['password' => Hash::make('password')]具有密码字的哈希值,而不是"密码".

最好的方法是这样的:

$input = Input::only(['username', 'email', 'password']);
$user = User::create($input);
Run Code Online (Sandbox Code Playgroud)

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

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

这意味着您不必费心哈希,并且可以相信模型会为您完成.

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

  • 对于像我这样的 Laravel 初学者 :) 请注意使用 `$this->attributes['password'] = Hash::make($value);` 而不是 `$this->password = Hash::make($value );` (2认同)