Skip to content

Instantly share code, notes, and snippets.

@markkimsal
Created November 13, 2019 13:53
Show Gist options
  • Save markkimsal/71f299ba5e2713c6b68ccb633f474bbc to your computer and use it in GitHub Desktop.
Save markkimsal/71f299ba5e2713c6b68ccb633f474bbc to your computer and use it in GitHub Desktop.
Laravel and JSON-API formatting
<?php
/**
* 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)
{
if ($request->expectsJson() || $request->acceptsAnyContentType()) {
if ($exception instanceof \Illuminate\Auth\Access\AuthorizationException) {
return response()->json(['errors'=>[ ['status'=>403, 'title'=>'Forbidden'] ]], 403);
}
if ($exception instanceof \Illuminate\Database\Eloquent\ModelNotFoundException) {
return response()->json(['errors'=>[ ['status'=>404, 'title'=>'Not Found'] ]], 404);
}
if ($exception instanceof \Illuminate\Validation\ValidationException) {
$errors = [];
foreach($exception->errors() as $field => $err) {
$errors[] = ['status'=>422, 'source'=>$field, 'title'=>'Validation Exception', 'message'=>$err[0]];
}
return response()->json(['errors'=> $errors ], 422);
}
}
return parent::render($request, $exception);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment