Created
January 16, 2019 06:53
-
-
Save abdullahbutt/55776f3fd83bb379e9dbc5384a7a6f6a to your computer and use it in GitHub Desktop.
laravel api validation response 422 solution
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
//location in Laravel Project: project_root\app\Exceptions\Handler.php | |
// I have modified the "render" method on line 51 (on line 48 in actual file in Laravel) | |
namespace App\Exceptions; | |
use Exception; | |
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler; | |
use Illuminate\Validation\ValidationException; | |
class Handler extends ExceptionHandler | |
{ | |
/** | |
* A list of the exception types that are not reported. | |
* | |
* @var array | |
*/ | |
protected $dontReport = [ | |
// | |
]; | |
/** | |
* A list of the inputs that are never flashed for validation exceptions. | |
* | |
* @var array | |
*/ | |
protected $dontFlash = [ | |
'password', | |
'password_confirmation', | |
]; | |
/** | |
* Report or log an exception. | |
* | |
* @param \Exception $exception | |
* @return void | |
*/ | |
public function report(Exception $exception) | |
{ | |
parent::report($exception); | |
} | |
/** | |
* Render an exception into an HTTP response. | |
* | |
* @param \Illuminate\Http\Request $request | |
* @param \Exception $exception | |
* @return \Illuminate\Http\Response | |
*/ | |
public function render($request, Exception $exception) | |
{ | |
//return parent::render($request, $exception); | |
if($request->isXmlHttpRequest() && $exception instanceof ValidationException) | |
{ | |
if ($exception instanceof ValidationException) { | |
//dd($this->invalidJson($request, $exception)->getData()->errors); | |
$data = $this->invalidJson($request, $exception)->content(); | |
$data = \GuzzleHttp\json_decode($data); | |
$errors = $data->errors; | |
$errorMessage = ''; | |
foreach ($errors as $key=>$val) | |
{ | |
$errorMessage = $errorMessage.$val[0]." "; | |
} | |
return response()->json([ | |
'status' => false, | |
'message' => $errorMessage, | |
'data' => $errors | |
]); | |
} | |
} | |
else | |
{ | |
return parent::render($request, $exception); | |
} | |
//dd($exception); | |
//return HelperModule::jsonApiResponse(false, $exception->getMessage()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Can you please remove commented code which is no more useful?