How to convert collection into JOSN in Laravel

Laravel uses collection classes as common data storage. But while creating APIs JSON is an idle data type to return response data instead of a collection.

In this tutorial, you will learn how to convert collection data into JSON strings. Those data can be a model instance or even a manually created collection. We will convert the collection object into a JSON string using multiple methods.

Here, we will take multiple examples with different methods because it's based on use case. Let's suppose, we are getting data from the database and you need to convert collection data into JSON then you can use toJson() collection method. Or you need to return JSON data as API response then you can use json() method of response class.

Last, you want to use the PHP json_encode method on collection then you use it. Let's take examples for all methods.

Using toJson() Method

The toJson() method is a collection method that converts the collection into JSON string. You can directly chain it into Eloquent query and get the value as JSON.

Before using this method we have to get data from Eloquent builder using get() or find() method. Let's take example of toJson() method:

<?php

namespace App\Http\Controllers;

use App\Models\User;

class HomeController extends Controller
{
    public function users(){
        $user = User::whereId(1)->get()->toJson();
        //OR
        $user = User::find(1)->toJson();

        return $user;
    }
}

In the above example, we will find user by ID and convert data into JSON objects. We just chain toJson() method on eloquent query builder.

Using json_encode() method

The json_encode() method is a primary function of PHP itself so we can use it without any dependency on Laravel. It required only one parameter which is data, there are also some optional flags like JSON_PRETTY_PRINT or JSON_NUMERIC_CHECK which we can pass.

<?php

namespace App\Http\Controllers;

use App\Models\User;

class HomeController extends Controller
{
    public function users(){
        $users = User::latest()
            ->take(10)
            ->get();

        return json_encode($user);
    }
}

JSON Response Method

The JSON response method uses a response class to convert array or collection data into JSON object While creating APIs, the json() function is used to convert the collection into JSON and return it as a response.

<?php

namespace App\Http\Controllers;

use App\Models\User;

class HomeController extends Controller
{
    public function users(){
        $users = User::latest()
            ->take(10)
            ->get();

        return response()->json($user);
    }
}

Conclusion

In this article, we have converted the collection into JSON object by multiple ways like toJson() function, json() method, and json_encode() function.