在用户模型上创建方法(bcrypt)

问题描述 投票:1回答:3

在查看新的laravel版本5.4后,我注意到使用“$user = User::create(request(['name', 'email','password']));”时密码不会自动加密密码,是我,还是默认密码在模型创建方法上哈希?我不记得了,但是不应该认为方法“创造”已经这样做了吗?

laravel laravel-5.4
3个回答
1
投票

正如Laravel Docs所述

如果您使用Laravel应用程序附带的内置LoginController和RegisterController类,它们将自动使用Bcrypt进行注册和身份验证。

如果您使用Laravel中提供的RegisterController.php,您不需要手动输入Hash密码,否则您需要使用

 return User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => bcrypt($data['password']), //<==encrypt here
        ]);

检查寄存器控制器:

https://github.com/laravel/laravel/blob/master/app/Http/Controllers/Auth/RegisterController.php#L63


1
投票

试试以下内容。

namespace App \ Http \ Controllers;

使用Illuminate \ Http \ Request;

使用Illuminate \ Support \ Facades \ Hash;

使用App \ User;

class RegistrationsController扩展Controller {

public function store()
{
    //validate the form
    $this->validate(request(),[
        'name'=> ['required', 'string', 'max:255'],
        'email'=> ['required', 'string', 'email', 'max:255', 'unique:users'],
        'password'=>['required', 'string', 'min:4', 'confirmed'],
    ]);

    //create and save the user

        $user =User::create([
       'name'=>request('name'), 
       'email'=>request('email'),

        //hash your password 

       'password'=>Hash::make(request('password'))
       ]);

    //sign in the user
    auth()->login($user);

    //redirect to the homepage
     return redirect()->home();
}

}


0
投票

在用户模型中,您需要添加以下功能,以加密默认密码。

public function setPasswordAttribute($value)
        {
            if($value != ""){
                $this->attributes['password'] = bcrypt($value);
            }
        }
© www.soinside.com 2019 - 2024. All rights reserved.