Laravel Json Response Not working as expected - laravel

Unable to get response while response object is empty. Works perfect when the object has data returned.
public function show($id)
{
$associates = Associate::find_by_id($id);
if(count($associates)<1)
{
$output = array('message' => 'No Records Found');
$status = 204;
}
else{
$output = array('message' => 'success','data'=>$associates);
$status = 200;
}
return response()->json($output,$status);
}
There is no response when the $associate object is empty.
Response when $associate is not empty:
{
"message": "success",
"data": [
{
"first_name": "xxx",
"last_name": "xxx",
"mobile": xxxxxxxxxx,
"email": "xxxxxx#xxxxx",
"city": "xxxxx",
"state": "xxxxxx",
"pincode": "xxxxx"
}
]
}

I had the same issue for status code 204 .
I believe this is caused here. The Illuminate\Foundation\Application class is then catching this and throwing an HttpException.
I believe the simplest fix would be to make the controller return the following instead:
return Response::make("", 204);
Returning a empty message.
check status_code in your code to display message in frontend .

It will be easier if you use route model binding to find the ID of the record. For more information check https://laravel.com/docs/5.7/routing#route-model-binding.
I think the snippet below should work.
if ($associates) {
$output = array('message' => 'success','data'=>$associates);
$status = 200;
} else {
$output = array('message' => 'No Records Found');
$status = 204;
}

I've rewrote the function for your reference.
BTW. If the function return only one record, use singular noun for variable name in general.
public function show($id)
{
// Use find() instead of find_by_id()
$associate = Associate::find($id);
// $associate will be null if not matching any record.
if (is_null($associate)) {
// If $associate is null, return error message right away.
return response()->json([
'message' => 'No Records Found',
], 204);
}
// Or return matches data at the end.
return response()->json([
'message' => 'success',
'data' => $associate,
], 204);
}

Related

Laravel API - Display all districts when state field is empty

Below given is my code to display the specific districts of an inputted state. But in this code itself, i want to display all districts in the db if the state field is empty. How to modify my code to get such an output. So, my desired API works such that it returns all the districts when the api is called. And only if the state field is inputted, it shows the particular districts specific to it. Help me with ur suggestions.
public function state_lookup(Request $request)
{
$validator = Validator::make
($request->all(),
[
'state' => 'string',
]
);
if ($validator->fails()) {
return response()->json(
[$validator->errors()],
422
);
}
if(empty($request->state)){
$dist=PersonalDetails::get(['district']);
return response()->json($dist);
}
$data = PersonalDetails::where('state',$request->state)->get(['district']);
// dd($data);
if(count($data)){
return response()->json(['message'=>'success','data'=>$data]);
}
else{
return response()->json(['message'=>'Invalid State']);
}
}
in failure case,I am getting json result as below
{
"message": "success",
"data": []
}
it shows "success" instead of "invalid state"
You can use when
$data = PersonalDetails::when(!empty($request->state),function ($query)use($request){
$query->where('state',$request->state);
})->get(['district']);
or
$data = PersonalDetails::where(function ($query)use($request){
if(isset($request)&&!empty($request)){
$query->where('state',$request->state);
}
})->get(['district']);
To avoid 0 key in response change like below
if(count($data)){
return response()->json(['message'=>'success','data'=>$data]);
}
Try with this,
//In your controller
$request->validate([
'state' => 'string'
]);
// $request->validate it self return error messages you have to display
// for an example (write below code in your blade file)
#error('state')
<div class="alert alert-danger">{{ $message }}</div>
#enderror
// write below code in your controller file
$details = PersonalDetails::select('district');
$details->where(function($query) use($request) {
if (isset($request->state) && $request->state != '') {
$query->where('state', $request->state);
}
// do what you want to filter in your query like above
});
$data = $details->get();

Laravel API, how to properly handle errors

Anyone know what is the best way to handle errors in Laravel, there is any rules or something to follow ?
Currently i'm doing this :
public function store(Request $request)
{
$plate = Plate::create($request->all());
if ($plate) {
return $this->response($this->plateTransformer->transform($plate));
} else {
// Error handling ?
// Error 400 bad request
$this->setStatusCode(400);
return $this->responseWithError("Store failed.");
}
}
And the setStatusCode and responseWithError come from the father of my controller :
public function setStatusCode($statusCode)
{
$this->statusCode = $statusCode;
return $this;
}
public function responseWithError ($message )
{
return $this->response([
'error' => [
'message' => $message,
'status_code' => $this->getStatusCode()
]
]);
}
But is this a good way to handle the API errors, i see some different way to handle errors on the web, what is the best ?
Thanks.
Try this, i have used it in my project (app/Exceptions/Handler.php)
public function render($request, Exception $exception)
{
if ($request->wantsJson()) { //add Accept: application/json in request
return $this->handleApiException($request, $exception);
} else {
$retval = parent::render($request, $exception);
}
return $retval;
}
Now Handle Api exception
private function handleApiException($request, Exception $exception)
{
$exception = $this->prepareException($exception);
if ($exception instanceof \Illuminate\Http\Exception\HttpResponseException) {
$exception = $exception->getResponse();
}
if ($exception instanceof \Illuminate\Auth\AuthenticationException) {
$exception = $this->unauthenticated($request, $exception);
}
if ($exception instanceof \Illuminate\Validation\ValidationException) {
$exception = $this->convertValidationExceptionToResponse($exception, $request);
}
return $this->customApiResponse($exception);
}
After that custom Api handler response
private function customApiResponse($exception)
{
if (method_exists($exception, 'getStatusCode')) {
$statusCode = $exception->getStatusCode();
} else {
$statusCode = 500;
}
$response = [];
switch ($statusCode) {
case 401:
$response['message'] = 'Unauthorized';
break;
case 403:
$response['message'] = 'Forbidden';
break;
case 404:
$response['message'] = 'Not Found';
break;
case 405:
$response['message'] = 'Method Not Allowed';
break;
case 422:
$response['message'] = $exception->original['message'];
$response['errors'] = $exception->original['errors'];
break;
default:
$response['message'] = ($statusCode == 500) ? 'Whoops, looks like something went wrong' : $exception->getMessage();
break;
}
if (config('app.debug')) {
$response['trace'] = $exception->getTrace();
$response['code'] = $exception->getCode();
}
$response['status'] = $statusCode;
return response()->json($response, $statusCode);
}
Always add Accept: application/json in your api or json request.
Laravel is already able to manage json responses by default.
Withouth customizing the render method in app\Handler.php you can simply throw a Symfony\Component\HttpKernel\Exception\HttpException, the default handler will recognize if the request header contains Accept: application/json and will print a json error message accordingly.
If debug mode is enabled it will output the stacktrace in json format too.
Here is a quick example:
<?php
...
use Symfony\Component\HttpKernel\Exception\HttpException;
class ApiController
{
public function myAction(Request $request)
{
try {
// My code...
} catch (\Exception $e) {
throw new HttpException(500, $e->getMessage());
}
return $myObject;
}
}
Here is laravel response with debug off
{
"message": "My custom error"
}
And here is the response with debug on
{
"message": "My custom error",
"exception": "Symfony\\Component\\HttpKernel\\Exception\\HttpException",
"file": "D:\\www\\myproject\\app\\Http\\Controllers\\ApiController.php",
"line": 24,
"trace": [
{
"file": "D:\\www\\myproject\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\ControllerDispatcher.php",
"line": 48,
"function": "myAction",
"class": "App\\Http\\Controllers\\ApiController",
"type": "->"
},
{
"file": "D:\\www\\myproject\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Route.php",
"line": 212,
"function": "dispatch",
"class": "Illuminate\\Routing\\ControllerDispatcher",
"type": "->"
},
...
]
}
Using HttpException the call will return the http status code of your choice (in this case internal server error 500)
In my opinion I'd keep it simple.
Return a response with the HTTP error code and a custom message.
return response()->json(['error' => 'You need to add a card first'], 500);
Or if you want to throw a caught error you could do :
try {
// some code
} catch (Exception $e) {
return response()->json(['error' => $e->getMessage()], 500);
}
You can even use this for sending successful responses:
return response()->json(['activeSubscription' => $this->getActiveSubscription()], 200);
This way no matter which service consumes your API it can expect to receive the same responses for the same requests.
You can also see how flexible you can make it by passing in the HTTP status code.
If you are using Laravel 8+, you can do it simply by adding these lines in Exception/Handler.php on register() method
$this->renderable(function (NotFoundHttpException $e, $request) {
if ($request->is('api/*')) {
return response()->json([
'message' => 'Record not found.'
], 404);
}
});
For me, the best way is to use specific Exception for API response.
If you use Laravel version > 5.5, you can create your own exception with report() and render() methods. Use command:
php artisan make:exception AjaxResponseException
It will create AjaxResponseException.php at: app/Exceptions/
After that fill it with your logic. For example:
/**
* Report the exception.
*
* #return void
*/
public function report()
{
\Debugbar::log($this->message);
}
/**
* Render the exception into an HTTP response.
*
* #param \Illuminate\Http\Request $request
* #return JsonResponse|Response
*/
public function render($request)
{
return response()->json(['error' => $this->message], $this->code);
}
Now, you can use it in your ...Controller with try/catch functionality.
For example in your way:
public function store(Request $request)
{
try{
$plate = Plate::create($request->all());
if ($plate) {
return $this->response($this->plateTransformer->transform($plate));
}
throw new AjaxResponseException("Plate wasn't created!", 404);
}catch (AjaxResponseException $e) {
throw new AjaxResponseException($e->getMessage(), $e->getCode());
}
}
That's enough to make your code more easier for reading, pretty and useful.
Best regards!
For Laravel 8+ in file App\Exceptions\Hander.php inside method register() paste this code:
$this->renderable(function (Throwable $e, $request) {
if ($request->is('api/*')) {
return response()->json([
'message' => $e->getMessage(),
'code' => $e->getCode(),
], 404);
}
});
I think it would be better to modify existing behaviour implemented in app/Exceptions/Handler.php than overriding it.
You can modify JSONResponse returned by parent::render($request, $exception); and add/remove data.
Example implementation:
app/Exceptions/Handler.php
use Illuminate\Support\Arr;
// ... existing code
public function render($request, Exception $exception)
{
if ($request->is('api/*')) {
$jsonResponse = parent::render($request, $exception);
return $this->processApiException($jsonResponse);
}
return parent::render($request, $exception);
}
protected function processApiException($originalResponse)
{
if($originalResponse instanceof JsonResponse){
$data = $originalResponse->getData(true);
$data['status'] = $originalResponse->getStatusCode();
$data['errors'] = [Arr::get($data, 'exception', 'Something went wrong!')];
$data['message'] = Arr::get($data, 'message', '');
$originalResponse->setData($data);
}
return $originalResponse;
}
Well, all answers are ok right now, but also they are using old ways.
After Laravel 8, you can simply change your response in register() method by introducing your exception class as renderable:
<?php
namespace Your\Namespace;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
class Handler extends ExceptionHandler
{
/**
* Register the exception handling callbacks for the application.
*
* #return void
*/
public function register()
{
$this->renderable(function (NotFoundHttpException $e, $request) {
if ($request->is('api/*')) {
return response()->json([
'message' => 'Record not found.'
], 404);
}
});
}
}
Using some code from #RKJ best answer I have handled the errors in this way:
Open "Illuminate\Foundation\Exceptions\Handler" class and search for a method named "convertExceptionToArray". This method converts the HTTP exception into an array to be shown as a response. In this method, I have just tweaked a small piece of code that will not affect loose coupling.
So replace convertExceptionToArray method with this one
protected function convertExceptionToArray(Exception $e, $response=false)
{
return config('app.debug') ? [
'message' => $e->getMessage(),
'exception' => get_class($e),
'file' => $e->getFile(),
'line' => $e->getLine(),
'trace' => collect($e->getTrace())->map(function ($trace) {
return Arr::except($trace, ['args']);
})->all(),
] : [
'message' => $this->isHttpException($e) ? ($response ? $response['message']: $e->getMessage()) : 'Server Error',
];
}
Now navigate to the App\Exceptions\Handler class and paste the below code just above the render method:
public function convertExceptionToArray(Exception $e, $response=false){
if(!config('app.debug')){
$statusCode=$e->getStatusCode();
switch ($statusCode) {
case 401:
$response['message'] = 'Unauthorized';
break;
case 403:
$response['message'] = 'Forbidden';
break;
case 404:
$response['message'] = 'Resource Not Found';
break;
case 405:
$response['message'] = 'Method Not Allowed';
break;
case 422:
$response['message'] = 'Request unable to be processed';
break;
default:
$response['message'] = ($statusCode == 500) ? 'Whoops, looks like something went wrong' : $e->getMessage();
break;
}
}
return parent::convertExceptionToArray($e,$response);
}
Basically, we overrided convertExceptionToArray method, prepared the response message, and called the parent method by passing the response as an argument.
Note: This solution will not work for Authentication/Validation errors but most of the time these both errors are well managed by Laravel with proper human-readable response messages.
In your handler.php This should work for handling 404 Exception.
public function render($request, Throwable $exception ){
if ($exception instanceof ModelNotFoundException) {
return response()->json([
'error' => 'Data not found'
], 404);
}
return parent::render($request, $exception);
}
You don't have to do anything special. Illuminate\Foundation\Exceptions\Handler handles everything for you. When you pass Accept: Application/json header it will return json error response. if debug mode is on you will get exception class, line number, file, trace if debug is off you will get the error message. You can override convertExceptionToArray. Look at the default implementation.
return config('app.debug') ? [
'message' => $e->getMessage(),
'exception' => get_class($e),
'file' => $e->getFile(),
'line' => $e->getLine(),
'trace' => collect($e->getTrace())->map(function ($trace) {
return Arr::except($trace, ['args']);
})->all(),
] : [
'message' => $this->isHttpException($e) ? $e->getMessage() : 'Server Error',
];
As #shahib-khan said,
this happens in debug mode and is handled by Laravel in production mode.
you can see base method code in
\Illuminate\Foundation\Exceptions\Handler::convertExceptionToArray
protected function convertExceptionToArray(Throwable $e)
{
return config('app.debug') ? [
'message' => $e->getMessage(),
'exception' => get_class($e),
'file' => $e->getFile(),
'line' => $e->getLine(),
'trace' => collect($e->getTrace())->map(fn ($trace) => Arr::except($trace, ['args']))->all(),
] : [
'message' => $this->isHttpException($e) ? $e->getMessage() : 'Server Error',
];
}
Therefore, I overrode the the convertExceptionToArray function in app/Exceptions/Handler
of course, still in debug mode, if the exception is thrown, you can track it in the Laravel.log.
protected function convertExceptionToArray(Throwable $e)
{
return [
'message' => $this->isHttpException($e) ? $e->getMessage() : 'Server Error',
];
}
Add header to your API endpoint. which works for me. it will handle the error request properly.
Accept: application/json

How to produce API error responses in Laravel 5.4?

Whenever I make a call to /api/v1/posts/1, the call is forwarded to the show method
public function show(Post $post) {
return $post;
}
in PostController.php resourceful controller. If the post does exist, the server returns a JSON response. However, if the post does not exist, the server returns plain HTML, despite the request clearly expecting JSON in return. Here's a demonstration with Postman.
The problem is that an API is supposed to return application/json, not text/html. So, here are my questions:
1. Does Laravel have built-in support for automatically returning JSON if exceptions occur when we use implicit route model binding (like in show method above, when we have 404)?
2. If it does, how do I enable it? (by default, I get plain HTML, not JSON)
If it doesn't what's the alternative to replicating the following across every single API controller
public function show($id) {
$post = Post::find($id); // findOrFail() won't return JSON, only plain HTML
if (!$post)
return response()->json([ ... ], 404);
return $post;
}
3. Is there a generic approach to use in app\Exceptions\Handler?
4. What does a standard error/exception response contain? I googled this but found many custom variations.
5. And why isn't JSON response still built into implicit route model binding? Why not simplify devs life and handle this lower-level fuss automatically?
EDIT
I am left with a conundrum after the folks at Laravel IRC advised me to leave the error responses alone, arguing that standard HTTP exceptions are rendered as HTML by default, and the system that consumes the API should handle 404s without looking at the body. I hope more people will join the discussion, and I wonder how you guys will respond.
I use this code in app/Exceptions/Handler.php, probably you will need making some changes
public function render($request, Exception $exception)
{
$exception = $this->prepareException($exception);
if ($exception instanceof \Illuminate\Http\Exception\HttpResponseException) {
return $exception->getResponse();
}
if ($exception instanceof \Illuminate\Auth\AuthenticationException) {
return $this->unauthenticated($request, $exception);
}
if ($exception instanceof \Illuminate\Validation\ValidationException) {
return $this->convertValidationExceptionToResponse($exception, $request);
}
$response = [];
$statusCode = 500;
if (method_exists($exception, 'getStatusCode')) {
$statusCode = $exception->getStatusCode();
}
switch ($statusCode) {
case 404:
$response['error'] = 'Not Found';
break;
case 403:
$response['error'] = 'Forbidden';
break;
default:
$response['error'] = $exception->getMessage();
break;
}
if (config('app.debug')) {
$response['trace'] = $exception->getTrace();
$response['code'] = $exception->getCode();
}
return response()->json($response, $statusCode);
}
Additionally, if you will use formRequest validations, you need override the method response, or you will be redirected and it may cause some errors.
use Illuminate\Http\JsonResponse;
...
public function response(array $errors)
{
// This will always return JSON object error messages
return new JsonResponse($errors, 422);
}
Is there a generic approach to use in app\Exceptions\Handler?
You can check if json is expected in the generic exception handler.
// app/Exceptions/Handler.php
public function render($request, Exception $exception) {
if ($request->expectsJson()) {
return response()->json(["message" => $exception->getMessage()]);
}
return parent::render($request, $exception);
}
The way we have handled it by creating a base controller which takes care of the returning response part. Looks something like this,
class BaseApiController extends Controller
{
private $responseStatus = [
'status' => [
'isSuccess' => true,
'statusCode' => 200,
'message' => '',
]
];
// Setter method for the response status
public function setResponseStatus(bool $isSuccess = true, int $statusCode = 200, string $message = '')
{
$this->responseStatus['status']['isSuccess'] = $isSuccess;
$this->responseStatus['status']['statusCode'] = $statusCode;
$this->responseStatus['status']['message'] = $message;
}
// Returns the response with only status key
public function sendResponseStatus($isSuccess = true, $statusCode = 200, $message = '')
{
$this->responseStatus['status']['isSuccess'] = $isSuccess;
$this->responseStatus['status']['statusCode'] = $statusCode;
$this->responseStatus['status']['message'] = $message;
$json = $this->responseStatus;
return response()->json($json, $this->responseStatus['status']['statusCode']);
}
// If you have additional data to send in the response
public function sendResponseData($data)
{
$tdata = $this->dataTransformer($data);
if(!empty($this->meta)) $tdata['meta'] = $this->meta;
$json = [
'status' => $this->responseStatus['status'],
'data' => $tdata,
];
return response()->json($json, $this->responseStatus['status']['statusCode']);
}
}
Now you need to extend this in your controller
class PostController extends BaseApiController {
public function show($id) {
$post = \App\Post::find($id);
if(!$post) {
return $this->sendResponseStatus(false, 404, 'Post not found');
}
$this->setResponseStatus(true, 200, 'Your post');
return $this->sendResponseData(['post' => $post]);
}
}
You would get response like this
{
"status": {
"isSuccess": false,
"statusCode": 404,
"message": "Post not found"
}
}
{
"status": {
"isSuccess": true,
"statusCode": 200,
"message": "Your post"
},
"data": {
"post": {
//Your post data
}
}
}
You just use use Illuminate\Support\Facades\Response;.
then, make the return as am:
public function index(){
$analysis = Analysis::all();
if(empty($analysis)) return Response::json(['error'=>'Empty data'], 200);
return Response::json($analysis, 200, [], JSON_NUMERIC_CHECK);
}
And now you will have a JSON return....

Updates records more than one time on laravel

I am trying to update values in laravel. I have a userupdate profile api which I can update the values first time with given parameters and their values but 2nd time when I update same values it gives me user profile does not exist.
My Code is :
public function UpdateUserProfile(Request $request)
{
$id = $request->input('id');
$client_gender = $request->input('client_gender');
$client_age = $request->input('client_age');
$client_weight = $request->input('client_weight');
$client_height = $request->input('client_height');
$client_dob = $request->input('client_dob');
$profile= DB::table('clients')
->where('id',$id)
->update(['client_gender'=>$client_gender,'client_age'=>$client_age,'client_height'=>$client_height,'client_weight'=>$client_weight,'client_dob'=>$client_dob]);
if($profile)
{
$resultArray = ['status' => 'true', 'message' => 'User profile updated Successfully!'];
return Response::json( $resultArray, 200);
}
$resultArray = ['status' => 'false', 'message' => 'User profile does not exist!'];
return Response::json($resultArray, 400);}
first time when I update the value it gives me the response like this:
{
"status": "true",
"message": "User profile updated Successfully!"
}
and when I hit the update request through a postman it gives a 400 Bad request and response is :
{
"status": "false",
"message": "User profile does not exist!"
}
I'd recommend rewriting that function to look like the following; mostly because it reads better and uses the Model methods that are more commonly found in Laravel
public function UpdateUserProfile(Request $request)
{
// this code fails if there is no client with this id
$client = App\Client::findOrFail($request->id);
// attach new values for all of the attributes
$client->client_gender = $request->input('client_gender');
$client->client_age = $request->input('client_age');
$client->client_weight = $request->input('client_weight');
$client->client_height = $request->input('client_height');
$client->client_dob = $request->input('client_dob');
// save
$client->save();
return ['status' => 'true', 'message' => 'User profile updated Successfully!'];
}

Validating an API request in Laravel 5.1

I am creating a simple api using laravel 5.1 to create a row in a table and return the id of the newly created row.
I am able to do so, but when it comes to validating I am not sure what to do.
e.g.
transaction_request table
id|order_id|customer_id|amount
validation rules for order_id and customer_id is just required
my uri to request this is http://localhost:8000/api/v1/transactionRequests?order_id=123&customer_id=&amount=3300
note that customer_id is not defined. user is returned with following json.
{
"error": {
"code": "GEN-WRONG-ARGS",
"http_code": 400,
"message": "{\"customer_id\":[\"The customer_id field is required.\"]}"
}
}
See the message: with those '\', How do I fix that. I know, it is because, I use following validation method in my controller that throws the exception
public function validateRequestOrFail($request, array $rules, $messages = [], $customAttributes = [])
{
$validator = $this->getValidationFactory()->make($request->all(), $rules, $messages, $customAttributes);
if ($validator->fails())
{
throw new Exception($validator->messages());
}
}
and I use catch to deal with it as following
try {
if(sizeof(TransactionRequest::$rules) > 0)
$this->validateRequestOrFail($request, TransactionRequest::$rules);
} catch (Exception $e) {
return $this->response->errorWrongArgs($e->getMessage());
}
errorWrongArgs is defined as following
public function errorWrongArgs($message = 'Wrong Arguments')
{
return $this->setStatusCode(400)->withError($message, self::CODE_WRONG_ARGS);
}
public function withError($message, $errorCode)
{
return $this->withArray([
'error' => [
'code' => $errorCode,
'http_code' => $this->statusCode,
'message' => $message
]
]);
}
I want the response to be clean as following (btw i am using ellipsesynergie/api-response library and not the default response class, because I am using chrisbjr/api-guard)
{
"error": {
"code": "GEN-WRONG-ARGS",
"http_code": 400,
"message": {
"customer_id": "The customer_id field is required."
}
}
}
Yes, the problem was in my understanding of what $validator->messages() returns, it returns a MessageBag object which is more like a Json object. Where as Exception() expects a String message. Thus it treats the Json as a String by escaping quote character as \". Solution to this is I pass the Json string to Exception method but after I catch it I convert the Json String to an array using json_decode, which is then taken by my response class.
throw new Exception($validator->messages());
return $this->response->errorWrongArgs(json_decode($e->getMessage(),true));

Resources