【发布时间】:2020-06-02 06:38:53
【问题描述】:
我有一个自定义表单请求,我在其中执行了一些额外的验证逻辑,如果我的逻辑失败但我收到此错误,我想添加一个错误:
在 null 上调用成员函数 errors()
这是我的自定义请求:
if (!empty($this->get('new_password')) && !empty($this->get('current_password'))) {
if (
!Auth::attempt([
'email' => $this->get('email'),
'password' => $this->get('current_password'),
'status' => 'pending'
])
) {
$this->validator->errors()->add('current_password', 'Something is wrong with this field!');
}
}
return [
'first_name' => 'required|min:1|max:190',
];
编辑完整的课程
class ProfileRequest extends FormRequest
{
public function authorize()
{
return Auth::check();
}
public function rules()
{
if (!empty($this->get('new_password')) && !empty($this->get('current_password'))) {
if (
!Auth::attempt([
'email' => $this->get('email'),
'password' => $this->get('current_password'),
'status' => 'pending'
])
) {
$this->validator->getMessageBag()->add('current_password', 'Something is wrong with this field!');
}
}
return [
'first_name' => 'required|min:1|max:190',
];
}
}
【问题讨论】:
-
在 null 上调用成员函数 errors() 意味着 $this->validator 为 null。请检查你在哪里初始化了 $this->validator
-
@Sehdev 它来自扩展我的自定义表单请求的 FormRequest laravel.com/docs/5.8/validation#creating-form-requests
-
你能把全班的代码灌进去吗?
-
@V-K 查看完整代码编辑