LoginSignup
6
3

More than 5 years have passed since last update.

laravel5.5 フォームリクエストのバリデーションエラーをjsonで返す方法

Last updated at Posted at 2018-04-25

日本語のlaravel5.5 のドキュメントを参考にweb APIの実装をしているが、
バリデーションを行う時に、フォームリクエストを使用した場合、
バリデーションエラーをjsonで返す方法は書いていないため困った

http://www.coding4developers.com/tag/how-to-make-a-custom-formrequest-error-response-in-laravel-5-5/
上記URLによると
laravel5.5からカスタムバリデーションのバリデーションエラーからjsonを返す方法が変わったらしい

解決方法

フォームリクエストを作成しているクラスで
以下を記載すればjsonでバリデーションエラーを返してくれた。

例ファイル)/app/Http/Requests/UserFormRequest.php

use Illuminate\Contracts\Validation\Validator;
use Illuminate\Http\Exceptions\HttpResponseException;
protected function failedValidation(Validator $validator) 
        {
        throw new HttpResponseException(response()->json($validator->errors(), 422));
    }


参考サイト
Tag: How to make a custom FormRequest error response in Laravel 5.5
http://www.coding4developers.com/tag/how-to-make-a-custom-formrequest-error-response-in-laravel-5-5/

6
3
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
3