How to force FormRequest return json in Laravel 5.1?

前端 未结 5 1636
梦如初夏
梦如初夏 2020-12-05 02:25

I\'m using FormRequest to validate from which is sent in an API call from my smartphone app. So, I want FormRequest alway return json when validation fail.

I saw th

5条回答
  •  鱼传尺愫
    2020-12-05 03:19

    Based on ZeroOne's response, if you're using Form Request validation you can override the failedValidation method to always return json in case of validation failure.

    The good thing about this solution, is that you're not overriding all the responses to return json, but just the validation failures. So for all the other Php exceptions you'll still see the friendly Laravel error page.

    namespace App\Http\Requests;
    
    use Illuminate\Contracts\Validation\Validator;
    use Illuminate\Foundation\Http\FormRequest;
    use Illuminate\Http\Exceptions\HttpResponseException;
    use Symfony\Component\HttpFoundation\Response;
    
    class InventoryRequest extends FormRequest
    {
        protected function failedValidation(Validator $validator)
        {
            throw new HttpResponseException(response($validator->errors(), Response::HTTP_UNPROCESSABLE_ENTITY));
        }
    

提交回复
热议问题