LoginSignup
0
2

More than 1 year has passed since last update.

【Laravel】フォームリクエストのエラーレスポンスを json で返す

Posted at

API リクエストのバリデーションをフォームリクエストで行うとき、バリデーションエラーのときのレスポンスが意図していたものと違った( json で返ってこなかった)ので、 json でレスポンスされる方法を調べてみました。

エラーレスポンスを json で返す

エラーレスポンスの定義はfailedValidationメソッドをオーバーライドして書きます(ここがミソです)。failedValidationメソッドをオーバーライドしていないと、バリデーションエラーの場合にホームにリダイレクトされたりします。

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
// ↓追加する
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Http\Exceptions\HttpResponseException;

class ApiValidation 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 [
            'title' => 'required'
        ];
    }

    /**
     * エラー時のレスポンスを定義
     */
    protected function failedValidation(Validator $validator) {
        $res = response()->json([
            'status' => 400,
            'errors' => $validator->errors(),
        ], 400);
        throw new HttpResponseException($res);
    }
}

参考記事

0
2
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
0
2