Skip to content

Instantly share code, notes, and snippets.

@abdullahbutt
Created January 16, 2019 06:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save abdullahbutt/55776f3fd83bb379e9dbc5384a7a6f6a to your computer and use it in GitHub Desktop.
Save abdullahbutt/55776f3fd83bb379e9dbc5384a7a6f6a to your computer and use it in GitHub Desktop.
laravel api validation response 422 solution
<?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());
}
}
@mustafaredsignal
Copy link

Can you please remove commented code which is no more useful?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment