How to Handle JSON Responses in Laravel

How to Handle JSON Responses in Laravel

Comprehensive Guide to Returning JSON Data in Laravel

Introduction

When building APIs and modern web applications using Laravel, handling JSON responses efficiently is important. There are various methods to return JSON responses, ensuring seamless communication between the backend and frontend of an application. Returning data, success or error messages can be properly structured in Laravel.

Handling JSON Responses in Laravel

Using response()->json() helper

This method accept an array as first parameter with the status code and explicitly returns a JSON response.

    $data = [
        "name" => "techwithalemsbaja"
    ];

    return response()->json([
        'message' => 'Data retrieved successfully',
        'data' => $data
    ], Response::HTTP_OK);

Output

{
  "message": "Data retrieved successfully",
  "data": {
    "name": "techwithalemsbaja"
  }
}

HTTP Status Code

There are different status code in Laravel that can be accessed via the Response Facade

Response::HTTP_OK

Returning an Error JSON Response

For errors, you can return responses with appropriate HTTP status codes that represent error message such as 400, 401 etc.

return response()->json([
    'message' => 'Something went wrong'
    'data' => []
], Response::HTTP_BAD_REQUEST);
💡
There is no universally standardized format for structuring JSON response payloads. However, I prefer using status codes to indicate the type of response from the API rather than including a success field in the payload. Additionally, I use the data field to return either an array or a string, depending on the expected response, rather than separating message and data into distinct fields. That said, this article isn’t focused on response structuring—just a quick mention.

There are a couple of standard status code you can use in Laravel.

Returning JSON with Custom Headers

Custom headers can be added to the response() helper or Response facade as the third parameter.

    $data = [
        "name" => "techwithalemsbaja"
    ];

    return response()->json([
        'message' => 'Data retrieved successfully',
        'data' => $data
    ], Response::HTTP_OK, ['Content-Type' => 'application/json']);

Using Response::json Facade

Since i already have a Response usage. The alias name for the Response facade was automatically generated FacadesResponse by vscode extension but you could rename it to something else.

use Illuminate\Http\Response;
use Illuminate\Support\Facades\Response as FacadesResponse;

Route::get('/', function () {
    $data = [
        "name" => "techwithalemsbaja"
    ];

    return FacadesResponse::json([
        'success' => true,
        'message' => 'Data retrieved successfully',
        'data' => $data
    ], Response::HTTP_OK);
});

Returning an Array Directly

By default Laravel can automatically converts arrays to JSON.

    $data = [
        "name" => "techwithalemsbaja"
    ];

return [
    'success' => true,
    'message' => 'Data retrieved successfully',
    'data' => $data
];

Using API Resources (For Structured & Transformed Responses)

It’s best to use Laravel resource to structure and transform API responses.

You can use the command below to create a resource:

php artisan make:resource PostResource

Modify app/Http/Resources/PostResource.php:

use Illuminate\Http\Resources\Json\JsonResource;

class PostResource extends JsonResource
{
    public function toArray($request)
    {
        return [
            'ulid' => $this->ulid,
            'title' => $this->title,
            'content' => $this->content,
            'created_at' => $this->created_at,
        ];
    }
}

Usage of the Post Resource class in Controller to return a structured response.

  • To return structured and formatted all Posts Response using collection on PostResource:
 $posts = Post::with('user')->latest()->get();
 return PostResource::collection($posts);

  • Single Post formated and structured Response using new keyword:
        $post = Post::where('ulid', $ulid)->firstOrFail();
        return new PostResource($post);

Example of Single structured API response:

{
  "data": {
    "ulid": "01jkxjdr5r05pfmn3ge4x1kzdq",
    "title": "Qui ab repellat soluta saepe.",
    "content": "Commodi ullam architecto aspernatur molestiae quo quaerat. Et quo eum voluptas qui doloremque aut iusto. Architecto aliquid voluptatem aliquam voluptas provident aut. Deserunt voluptate quia occaecati deleniti aut explicabo doloremque dolores. Aspernatur id nesciunt voluptatibus iste fuga.",
    "created_at": "2 weeks ago"
  }
}
💡
Laravel's API structured resource ensure a consistent, flexible, and efficient response format across the application. It enhances easy data transformation, reduce payload response size, and improve maintainability for a scalable API.

In Laravel 11 while developing APIs you can register JSON responses globally for handling exceptions in the bootstrap/app.php:

<?php

use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Illuminate\Http\Response;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__.'/../routes/web.php',
        commands: __DIR__.'/../routes/console.php',
        health: '/up',
    )
    ->withMiddleware(function (Middleware $middleware) {
        $middleware->trustProxies(at: '*');
    })
    ->withExceptions(function (Exceptions $exceptions) {
        //NotFoundHttpException json response globally 
        $exceptions->renderable(function (NotFoundHttpException $e) {
            return response()->json([
                'message' => $e->getMessage(),
            ], Response::HTTP_NOT_FOUND);
        });

    })->create();

Anytime a NotFoundHttpException is thrown the response will be in json format as opposed to returning html response.

Conclusion

In this article we’ve learn in-depth about how to handle JSON responses in Laravel which is essential for building APIs. There are multiple approaches, from simple JSON responses using the helper or Facade to structured API resources and global exception handling. These techniques will help you handle and return JSON replies in Laravel apps in an efficient manner.

Find this article useful… kindly share with your network and feel free to use the comment section for questions, answers, and contributions.

💡
Follow me on Hashnode: Alemsbaja --- X: Alemsbaja---- Youtube: Tech with Alemsbaja to stay updated on more articles

Did you find this article valuable?

Support Alemoh Rapheal Baja by becoming a sponsor. Any amount is appreciated!