6
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

laravel API バリデーションエラー時にエラー内容をJSONで返す

Last updated at Posted at 2022-06-23

概要

方法

  1. FormRequestクラスを継承した独自のリクエストクラスを作成する。

  2. 任意のバリデーションルールを記載する。

  3. 独自のリクエストクラスに下記の内容を追記する。

    use Illuminate\Http\Exceptions\HttpResponseException;
    use Illuminate\Contracts\Validation\Validator;
    
    protected function failedValidation(Validator $validator)
    {
        $response['errors']  = $validator->errors()->toArray();
    
        throw new HttpResponseException(response()->json($response));        
    }
    
  4. 一例だが、独自のリクエストクラスに上記内容を追記した場合下記のようになる。

    ContentRequest.php
    <?php
    
    namespace App\Http\Requests;
    
    use Illuminate\Foundation\Http\FormRequest;
    use Illuminate\Http\Exceptions\HttpResponseException;
    use Illuminate\Contracts\Validation\Validator;
    
    class ContentRequest extends FormRequest
    {
        /**
         * Determine if the user is authorized to make this request.
         *
         * @return bool
         */
        public function authorize()
        {
            return true;
        }
    
        /**
         * Get the validation rules that apply to the request.
         *
         * @return array
         */
        public function rules()
        {
            return [
                'array' => ['sometimes', 'required', 'array', 'min:1'],
            ];
        }
    
        protected function failedValidation(Validator $validator)
        {
            $response['errors']  = $validator->errors()->toArray();
        
            throw new HttpResponseException(response()->json($response));        
        }
    }
    
6
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?