2017-02-07 36 views
1

參照這個stack question and answer我想我的錯誤驗證的響應格式,以更簡化的格式......因此,在自定義應用程序\ HTTP \請求\ CustomRequest我格式FormRequest驗證錯誤響應

public function rules() 

{ 
    return [ 
     'amt' => 'required|numeric|min:1000', 
     'year' => 'required|numeric|min:' . date_format(new \DateTime, 'Y'), 
     'user_id' => 'required', 
     'ratio' => 'required' 
    ]; 
} 

public function response(array $errors) 
    { 
     if ($this->expectsJson()) { 
      return response()->json(['messsage'=>'Cannot Validate','errors'=> $errors]); 
     } 

     return $this->redirector->to($this->getRedirectUrl()) 
             ->withInput($this->except($this->dontFlash)) 
             ->withErrors($errors, $this->errorBag); 
    } 

/** 
    * Format the errors from the given Validator instance. 
    * 
    * @param \Illuminate\Contracts\Validation\Validator $validator 
    * @return array 
    */ 
    protected function formatErrors(Validator $validator) 
    { 
     return []; 
    } 

在我的控制器我有

/** 
    * Store a newly created resource in storage. 
    * 
    * @param \Illuminate\Http\Request $request 
    * 
    * @return Response Header 201 
    */ 
    public function store(CustomFormRequest $request) 
    { 

     $requestData = $request->all(); 
     Budget::create($requestData); 

     return response([], 201); 
    } 

按照laravel文檔我只需要「typehint」的請求。不過,我的迴應總是如此。

{ 「ID」: 「validation_failed」, 「消息」: 「驗證 失敗。」, 「元」:{ 「錯誤」:{ 「AMT」:[{ 「規則」:「min.numeric 」, 「消息」: 「其 AMT必須至少1000」, 「參數」: 「1000」]}]}}}

,如果我改變了這沒有意義響應格式。我需要的是

{ 「ID」: 「validation_failed」, 「消息」: 「驗證 失敗」, 「錯誤」:[{ 「AMT」:{ 「消息」:「其 AMT絕至少1000.「}}]}

我不知道我應該做什麼在這一點上。那裏還有什麼?

+1

剛剛實現了覆蓋默認輸出的功能。所以,如果您仍然需要它,只需查看包裝的自述文件即可。 –

回答

1

側信道通信(IRC)揭示肯德爾使用lanin/laravel-api-exceptions。這個包有一個自定義異常處理程序,它將Laravel的內置ValidationException更改爲自定義異常類和自定義輸出處理。提示輸出不是由Laravel生成的,可以是json輸出中的meta鍵,Laravel不會生成該輸出。

這個問題提到了FormRequest的response(array $errors)formatErrors(Validator $validator)方法,但是這些不被這個包使用。

驗證失敗JSON結果可以通過重寫自定義異常處理程序的renderForApi方法,檢查ValidationFailedApiException,並返回這些自定義響應進行修改。

-1

要有一個自定義錯誤消息,我想你正在尋找messages方法。在該方法上,只需返回一個數組。

例子:['fieldName.rule' => 'Custom message']

參見:https://laravel.com/api/5.3/Illuminate/Foundation/Http/FormRequest.html#method_messages

獎勵:如果你要來命名字段名稱只是做一個attributes方法。

參見:https://laravel.com/api/5.3/Illuminate/Foundation/Http/FormRequest.html#method_attributes

+0

我真的不想改變文本消息,但更多的JSON對象結構....查看更新的問題 – Kendall