【发布时间】:2020-08-25 12:46:16
【问题描述】:
问题
嘿
我已经处理一个问题几个小时了,我完全被它弄糊涂了。 在 Laravel 7.4.0 中使用 FormRequest 我有以下验证规则,请注意电子邮件:
<?php
namespace App\Http\Requests\API\Auth;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
class SignupRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'username' => 'string|required',
'email' => [
'email',
'unique:App\Models\User,email',
'confirmed',
'required'
],
'password' => 'string|required|min:8|confirmed|',
'security_question' => 'string|required',
'answer' => 'string|required'
];
}
}
控制器中的一个函数:
public function signup(SignupRequest $request) {
$securityQuestion = (new SecurityQuestion)->whereUuid($request['security_question'])->firstOrFail();
if ($securityQuestion['answer'] !== $request['answer']) {
return response()->json([
'message' => 'Svaret var forkert'
], 401);
}
$request['password'] = Hash::make($request['password']);
$request['activation_token'] = Str::random(60);
$user = (new User)->create([
'username' => $request['username'],
'email' => $request['email'],
'password' => $request['password'],
'activation_token' => $request['activation_token']
]);
$avatar = (new Avatar)
->create($user->username)
->getImageObject()
->encode('png');
Storage::disk('local')->put('public/avatars/' . $user->uuid . '/avatar.png', (string) $avatar);
$user->notify(new ActivationEmail());
return response()->json([
'message' => 'Successfully created user'
], 201);
}
使用这个我遇到了一个问题,我突然收到了这个回复:
{
"message": "The given data was invalid.",
"errors": {
"email": [
"The email has already been taken."
]
}
}
使用的数据,在尝试之间更改了电子邮件:
{
"username": "username",
"email": "nonactivated382@tester.dk",
"email_confirmation": "nonactivated382@tester.dk",
"password": "nonactivated2",
"password_confirmation": "nonactivated2",
"security_question": "a88a4e3a-78ae-4855-9630-053d606f94fa",
"answer": "world"
}
现在我可以 100% 肯定地告诉您,电子邮件还没有被接收,特别是因为奇怪的部分是函数执行,将其输入数据库,发送电子邮件,然后返回错误而不是成功。
我尝试过的
- 我把返回点改在User->create()之前,返回没问题
- 立即设置会导致同样的问题
- 对验证规则使用通常的单行样式
- 在验证规则中指定表而不是模型
- 使用 Arr::only 指定模型创建的不同值
- 只需为其提供 $request 变量作为模型创建的输入
- 使用不同的电脑
- 使用不同的数据库和版本
- 使用不同版本的 PHP
- 使用不同的操作系统
- 使用 Rule::unique() 方法
- 重新启动开发服务器、电脑、数据库。
- 使用 $data = $request->validated(),并使用 $data 变量而不是直接的 $request
- 删除电子邮件发送
- 注释除 model->create() 之外的所有内容
以上都没有改变问题,除了在决定发表这篇文章之前的最后几次尝试之外,这里的 JSON 被添加到响应中,仍然不知道为什么。返回删除和添加内容不会改变结果,因此这只是作为问题的一部分永久添加:
"password": [
"The password confirmation does not match."
]
它仍然会创建用户并发送电子邮件。
现在据我所知,问题似乎是在创建模型时发生了验证错误。奇怪的是,唯一的验证规则,即失败,在它刚刚允许通过的模型上失败,创建然后失败。据我所知,这是不可能的。从文档中的请求生命周期页面来看。日志中没有任何内容。
我希望有人能提供帮助,因为我完全不知道是什么原因造成的。
【问题讨论】: