0

我试图使用Laravel验证来生成自定义错误消息,但是我无法找到我应该重写的函数。如何在Laravel 5.5中为选定的请求类设置自定义响应

路线:POST:/entries/使用[email protected]其使用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类中实现此目的?

回答

5

如果你想定制只对选定的Request类验证响应时,需要添加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); 
} 

这样你就不需要在处理程序改变任何东西,有这种风俗只对这个班级做出反应。

如果你想全局更改格式的所有响应您应该添加到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); 
} 

可以在异常格式部分

+0

韩元也了解这Upgrade guide为所有验证定义这样的回答?我能做些什么才能为给定的Request类定义上述格式? – eithed

+0

@eithed我已经更新了我的答案 –

+0

傻我 - 我一直在看这个方法,甚至在'ApiRequest'类中覆盖它作为'protected function failedValidation(Validator $ validator)''我已经得到了一个'类App \ Api \ V1 \ Requests \ EntryStoreRequest不存在'这不能解释任何东西。您的回答也为我提供了解释:)谢谢! – eithed

相关问题