2017-06-26 95 views
-1

我正在開發一個API,該API也應提供有關驗證問題的消息。Laravel總是返回json中驗證錯誤的錯誤包

當「硬編碼」驗證我做這樣的事情

if ($validator->fails()) { 
    return response()->json($validator->errors(), 400); 
} 

這工作不錯 - 但我希望有一個「通用」的解決方案,基本上趕上所有ValidationExceptions做上述相同。

我已經嘗試過在Handler.php

public function render($request, Exception $exception) 
{ 
    $message = $exception->getMessage(); 

    if (is_object($message)) { 
     $message = $message->toArray(); 
    } 

    if ($exception instanceof ValidationException) { 
     return response()->json($message, 400); 
    } 

    ... 
} 

渲染功能,玩不過我找不到回來,我想

回答

0

這是有點愚蠢的實際相關數據的一個適當的方式 - 實際上拉拉維爾已經提供了我想要的。處理器擴展的ExceptionHandler其作用:

public function render($request, Exception $e) 
{ 
    $e = $this->prepareException($e); 

    if ($e instanceof HttpResponseException) { 
     return $e->getResponse(); 
    } elseif ($e instanceof AuthenticationException) { 
     return $this->unauthenticated($request, $e); 
    } elseif ($e instanceof ValidationException) { 
     return $this->convertValidationExceptionToResponse($e, $request); 
    } 

    return $this->prepareResponse($request, $e); 
} 

和convertValidationExceptionToResponse:

if ($e->response) { 
     return $e->response; 
    } 

    $errors = $e->validator->errors()->getMessages(); 

    if ($request->expectsJson()) { 
     return response()->json($errors, 422); 
    } 

    return redirect()->back()->withInput(
     $request->input() 
    )->withErrors($errors); 

所以,正是我想要的

+0

如果你總是希望它返回JSON,你可以做驗證文檔說的方式:'$ this-> validate($ request,$ rules,$ messages)'並覆蓋'Illuminate \ Foundation \ Validation \ ValidatesRequests'特性中的方法'buildFailedValidationResponse',以便它始終構建一個json響應。 – Bryan