Eloquent: How to Convert Query Result to JSON

Updated: January 18, 2024 By: Guest Contributor Post a comment

Introduction

When developing applications with Laravel, interacting with databases is streamlined using the Eloquent ORM. Eloquent allows for fluent query building and ORM functionality that elegantly works with the database. An often necessary feature is to convert query results to JSON format, which is particularly useful in API development and when dealing with AJAX requests in web applications.

In this tutorial, we will explore multiple ways to convert Eloquent query results into JSON. We will cover not just the basics but also dive into some advanced scenarios and best practices.

Returning Models & Collections as JSON

The simplest way to convert a query result to JSON in Eloquent is by returning an Eloquent model or collection directly from a route or a controller. Laravel automatically serializes the model to JSON when a response is created.

// Fetch a model instance
$book = Book::find(1);

// Return a JSON response containing the model data
return response()->json($book);

Eloquent collections are also automatically converted to JSON when returned from a route or controller:

// Fetch all books
$books = Book::all();

// Return a JSON response containing the collection
return response()->json($books);

Using the toJson Method

Eloquent models and collections provide a toJson method that converts the query result to a JSON string. Here is how you can use it:

// $book is an instance of an Eloquent model
$bookJson = $book->toJson();

// Echo the JSON string
echo $bookJson;

This method also takes an optional argument for specifying the JSON encoding options, such as JSON_PRETTY_PRINT:

// Convert to pretty-printed JSON
$bookJson = $book->toJson(JSON_PRETTY_PRINT);

// Display the JSON
echo $bookJson;

Working with Resource Classes

When you need fine-grained control over the JSON structure, Laravel’s resource classes come in handy. You can create a resource to transform the Eloquent model into an array. This array is then automatically converted to JSON when the resource is returned from a route or controller.

Here is how to create a simple resource:

php artisan make:resource BookResource

Once created, you can define the transformation in the toArray method of the resource:

class BookResource extends JsonResource
{
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'title' => $this->title,
            'author' => $this->author,
            // other fields...
        ];
    }
}

To return a single book:

$book = Book::find(1);
return new BookResource($book);

For a collection of books:

$books = Book::all();
return BookResource::collection($books);

Handling Relationships and Pagination

Oftentimes, Eloquent queries involve relationships or pagination. Here’s how to deal with these scenarios:

With Relationships

If the book has a relationship, say a ‘reviews’ relation, you may want to include these in your response:

return new BookResource($book->load('reviews'));

Using Pagination

If you use pagination, return paginated results directly in your response:

$books = Book::paginate(10);
return BookResource::collection($books);

Paginated results provide additional meta information such as the current page, total pages, and links for navigation.

API Resource Responses

If you’re using Laravel’s API routes, you may return API resource responses directly:

use Illuminate\Http\Resources\Json\JsonResource;

//... within controller method:

$books = Book::all();
return JsonResource::collection($books);

API resource responses automatically set the appropriate response headers for JSON content.

Customizing the JSON Response

To alter the JSON response globally or add meta information, you can use the with method provided on collections or the additional method on resources.

return (new BookResource($book))->additional(['meta' => [ 'version' => '1.0' ]]);

Conclusion

Converting Eloquent query results to JSON in Laravel is straightforward thanks to its built-in support for JSON serialization. From the simplicity of returning models and collections as JSON, to the extended functionalities of Eloquent resource classes, Laravel equips you with a robust set of tools to shape your data as needed for API consumption and frontend applications.

Keep on building amazing features by further exploring the powers of Laravel’s Eloquent ORM!