I'm trying to use Laravel validation to generate custom error message, however I'm unable to find the function I should be overriding.

路由:POST:/entries/使用EntryController@storeEntryController@store使用EntryStoreRequest执行验证.

EntryStoreRequest

namespace App\Api\V1\Requests;

class EntryStoreRequest extends ApiRequest
{
    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'message' => [
                'string',
                'required',
                'max:65535',
            ],
            'code' => [
                'string',
                'max:255',
                'nullable'
            ],
            'file' => [
                'string',
                'max:255',
                'nullable'
            ],
            'line' => [
                'string',
                'max:255',
                'nullable'
            ],
            'stack' => [
                'string',
                'max:65535',
                'nullable'
            ]
        ];
    }
}

ApiRequest

namespace App\Api\V1\Requests;

use Illuminate\Foundation\Http\FormRequest;

abstract class ApiRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }
}

当前返回的错误为:

{
    "message": "The given data was invalid.",
    "errors": {
        "message": [
            "The message field is required."
        ]
    }
}

我想把它们格式化为:

{
    "data": [],
    "meta: {
        "message": "The given data was invalid.",
        "errors": {
            "message": [
                "The message field is required."
            ]
        }
}

我怎样才能在ApiRequest个班里做到这一点?

推荐答案

如果只想为选定的请求类自定义验证响应,则需要向该类添加failedValidation()条消息:

protected function failedValidation(\Illuminate\Contracts\Validation\Validator $validator)
{
    $response = new JsonResponse(['data' => [], 
             'meta' => [
                'message' => 'The given data is invalid', 
                'errors' => $validator->errors()
             ]], 422);

    throw new \Illuminate\Validation\ValidationException($validator, $response);
}

This way you don't need to change anything in Handler and have this custom response only for this single class.

如果您想全局更改所有响应的格式,则应将以下方法添加到app\Exceptions\Handler.php文件中:

protected function invalidJson($request, ValidationException $exception)
{
    return response()->json([
             'data' => [], 
             'meta' => [
                'message' => 'The given data is invalid', 
                'errors' => $exception->errors()
             ]
             ], $exception->status);
}

你也可以在Exception Format节的Upgrade guide节中读到这方面的内容

Laravel相关问答推荐

Laravel模型嵌入嵌套模型时只附加属性

Laravel使用PostgreSQL显示";`try 读取null`上的属性,而不是SQL错误消息

Laravel 语法 GroupBy 获取列到数组

使用 fetch api 时 Laravel 控制器不存在错误

laravel 如何验证跨越午夜的两个值之间的时间(15:00 > 时间 > 01:00)

Laravel 从 5.1 升级到 5.2.0 错误

try 发布 AJAX 请求时 POST 405(方法不允许)-Laravel 4

使用命令行界面停止 laravel 服务器

语法错误或访问冲突:1115 未知字符集:utf8mb4

Laravel 如何处理来自浏览器的 PUT 请求?

安卓 retrofit |发布自定义对象(将 json 发送到服务器)

在 laravel 5 中的表单请求验证后传递旧输入

Laravel 将 JSON 转换为数组?

如何比较laravel中的两个加密(bcrypt)密码

在 laravel 6.0 中未定义命令ui

如何在laravel 5.1中使用url(路由)传递多个参数

Laravel 应用程序连接数据库时速度很慢

Laravel - 使用 Eloquent 查询构建器在 Select 中添加自定义列

在哪里放置 Blade::extend

Laravel 更新后用户模型错误(用户类包含 3 个抽象方法)