如何更改自定义FormRequest的http响应状态?

时间:2019-05-09 11:56:48

标签: laravel laravel-5

我使用以下类来验证传入请求:

class CreateInvoiceRequest extends FormRequest
{

    public function authorize(Request $request)
    {
        return true;

    }

    public function messages()
    {
        return [
            'name.required' => 'The name is required.',
            'name.string' => 'The name should be a string',
            'code.required' => 'Code',
              'code.string' => 'Code',
              'type.required' => 'Type'
        ];
    }

    public function rules()
    {
        return [
            'name' => 'required|string',
            'type' => 'string',
            'code' => ['required', 'string', new InvoiceCode],
        ];
    }
}

如果失败,它将以{errors: "The given data was invalid."}对象和http状态200返回数据。

如何以及在何处更改此状态?更多全球性的问题,如何在Laravel中处理错误和警告?

1 个答案:

答案 0 :(得分:2)

您可以向FormRequest的ValidationException方法中引发的failedValidation添加HTTP状态:

use Illuminate\Contracts\Validation\Validator;
use Illuminate\Validation\ValidationException;

class CreateInvoiceRequest extends FormRequest
{
    // ...

    protected function failedValidation(Validator $validator)
    {
        throw (new ValidationException($validator))
                    ->status(500)
                    ->errorBag($this->errorBag)
                    ->redirectTo($this->getRedirectUrl());
    }

    // ...

}