我有一个自定义表单请求,在其中执行了一些额外的验证逻辑,如果逻辑失败,我想添加一个错误,但出现此错误:
在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',
];
}
}
答案 0 :(得分:3)
我认为您需要按照laravel文档的建议添加钩子withValidator
。
public function withValidator($validator)
{
$validator->after(function ($validator) {
if ($this->somethingElseIsInvalid()) {
$validator->errors()->add('field', 'Something is wrong with this field!');
}
});
}