我有一种用户注册方法。我正在尝试清除代码,将请求类中的传递属性传递给create方法。
注册方法
public function register(CreateUserRequest $createUser)
{
$user = User::create($createUser->validated());
return response()->json($user);
}
CreateUserRequest类
class CreateUserRequest extends FormRequest
{
public function authorize()
{
return true;
}
public function rules()
{
return [
'first_name' => 'required',
'last_name' => 'required',
'username' => 'required',
'email' => 'required|email|unique:users,email',
'phone_number' => 'required|unique:users,phone_number|phone:IE',
'password' => 'required',
];
}
public function messages()
{
return [
'phone_number.phone' => 'The phone number is invalid.',
];
}
}
除了我的密码以纯文本格式存储外,这非常有效。如何使用bcrypt()对其加密,而不必编写要存储在create方法中的每个属性?
答案 0 :(得分:0)
我将首先获取数据,更新要哈希的密码,然后创建用户。
public function register(CreateUserRequest $createUser)
{
$userData = $createUser->validated();
$userData['password'] = Hash::make($userData['password']);
$user = User::create($userData);
return response()->json($user);
}
注意:不要忘记导入Illuminate \ Support \ Facades \ Hash;
use Illuminate\Support\Facades\Hash;