簡體   English   中英

如何更改 Laravel 驗證錯誤消息

[英]How to change laravel validation error message

我知道 laravel 為每個驗證規則提供了可自定義的錯誤消息,但是有沒有辦法更改 json 結果的message部分? 我似乎無法在文檔上找到任何內容。

{
    "message": "The given data was invalid.",
    "errors": {
        "email": [
            "The email has already been taken."
        ]
    }
}

在您的場地類上添加自定義消息,如下所示:

public static function messages($id = '') {
return [
    'name.required' => 'You must enter your name',
    'logo.required' => 'You must upload logo',
    'key.rules' => 'your messages'
];

並在您的控制器上添加消息作為第三個參數。

$this->validate($request, Venue::rules(), Venue::messages());

您絕對可以創建自己的 Exception 類並指示 laravel 使用它來回復響應。

假設你自己的自定義 Exception 類是Illuminate\\Http\\Exceptions\\HttpResponseException你只需要在你的表單請求類中覆蓋failedValidation方法並有這樣的東西。

use Illuminate\Http\Response;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Http\Exceptions\HttpResponseException;

...

/**
 * @param Validator $validator
 * @throws HttpResponseException
 */
protected function failedValidation(Validator $validator)
{
    throw new HttpResponseException(
        response()->json(
            [
                'message' => 'My message',
                'errors' => $validator->errors()->get('*') //or ->all() instead of get()
            ],
            Response::HTTP_UNPROCESSABLE_ENTITY
        )
    );
}

以上將確保使用您的自定義錯誤響應格式。 您還可以將其添加到 Trait 並將其包含在您的所有請求類中,或者只創建一個其他人應該擴展的基本請求類。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM