【问题标题】:How to set custom response for selected Request class in Laravel 5.5如何在 Laravel 5.5 中为选定的请求类设置自定义响应
【发布时间】:2018-03-22 01:18:20
【问题描述】:

我正在尝试使用 Laravel 验证来生成自定义错误消息,但是我找不到我应该覆盖的函数。

路由:POST:/entries/ 使用 EntryController@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 类中实现这一点?

【问题讨论】:

    标签: laravel laravel-5 laravel-5.5 laravel-request laravel-response


    【解决方案1】:

    如果您只想为选定的请求类自定义验证响应,则需要在该类中添加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);
    }
    

    这样您无需更改 Handler 中的任何内容,并且仅为该单个类提供此自定义响应。

    如果您想全局更改所有响应的格式,您应该将以下方法添加到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 中阅读有关此内容

    【讨论】:

    • 不会为所有验证定义这样的响应吗?我能做些什么来为给定的 Request 类定义上述格式?
    • 愚蠢的我 - 我以前一直在研究这种方法,甚至在 ApiRequest 类中将其覆盖为 protected function failedValidation(Validator $validator) ,我得到了一个 Class App\Api\V1\Requests\EntryStoreRequest does not exist 这并没有真正解释任何事物。您的回答也为我提供了一个解释:) 谢谢!
    • 感谢您的回答。这个对我有用。真的很有帮助。谢谢@MarcinNabiałek
    【解决方案2】:

    对于那些不想使用 JsonResponse 的人,这是我为我所做的

    protected function failedValidation(Validator $validator) {
            // if you want, log something here with $this->validationData(), $validator->errors()
            
            $response = redirect($this->getRedirectUrl())
                ->with('var1', 'my var 1') // custom flash variable to send if needed
                ->with('var2', 'my var 2')
                ->withErrors($validator)
                ->withInput();
            
            throw new ValidationException($validator, $response);
        }
    

    【讨论】:

      猜你喜欢
      • 2018-03-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-15
      • 1970-01-01
      相关资源
      最近更新 更多