Laravel在自定义表单请求中向验证器添加错误消息

时间:2020-02-18 09:26:00

标签: php laravel

我有一个自定义表单请求,在其中执行了一些额外的验证逻辑,如果逻辑失败,我想添加一个错误,但出现此错误:

在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',
        ];
    }
}

1 个答案:

答案 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!');
        }
    });
}
相关问题