3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Laravel】validationのエラーメッセージ「The given data was invalid.」をカスタマイズする

Posted at

確認バージョンは Laravel 7.26.1

FormRequestのバリデーションを追って見るとこんな感じ

1. config/app.phpのproviders
2. Illuminate\Foundation\Providers\FoundationServiceProvider::class
3. vendor/laravel/framework/src/Illuminate/Foundation/Providers/FormRequestServiceProvider::boot
4. vendor/laravel/framework/src/Illuminate/Validation/ValidatesWhenResolvedTrait::validateResolved
5. vendor/laravel/framework/src/Illuminate/Validation/ValidatesWhenResolvedTrait::failedValidation
6. vendor/laravel/framework/src/Illuminate/Validation/ValidationException::__construct

vendor/laravel/framework/src/Illuminate/Validation/ValidationException::__construct
でexceptionのメッセージをThe given data was invalid.でハードコーディングしているのが問題である

なのでapp/Exceptions/Handler.phpをカスタマイズする。
HandlerはIlluminate\Foundation\Exceptions\Handlerを継承しているので、そのソースを参考に下記メソッドをオーバーライド

    /**
     * Convert a validation exception into a JSON response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Illuminate\Validation\ValidationException  $exception
     * @return \Illuminate\Http\JsonResponse
     */
    protected function invalidJson($request, ValidationException $exception)
    {
        return response()->json([
            'message' => $exception->getMessage() === 'The given data was invalid.' ? '指定されたデータは無効でした。' : $exception->getMessage(),
            'errors' => $exception->errors(),
        ], $exception->status);
    }

うーん…ハードコーディングしてる方が悪いと思う。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?