Laravel 10 Collection โ€“ Using toJson() Method

The toJson() method in Laravel Collection makes it simple to convert the collection into JSON format. It essentially uses PHP's built-in json_encode() function under the hood. If needed, you can also provide the $options parameter, which works similarly to the json_encode function and is a set of predefined JSON constants.

Table of Contents

  1. Create a new Laravel Project
  2. Signature
  3. Example 1
  4. Output
  5. Example 2
  6. Output
  7. toJson() and Deep Nested Data Structures

Create a new Laravel Project

Creating the Laravel app is not necessary for this step, but if you haven't done it yet, you can proceed by executing the following command

composer create-project laravel/laravel laravel_collection

Signature

The signature of toJson() method in the Illuminate/Support/Collection class looks something like below.

/**
 * Get the collection of items as JSON.
 *
 * @param  int  $options
 * @return string
 */
public function toJson($options = 0)
{
    return json_encode($this->jsonSerialize(), $options);
}

Example 1

In the example below, we can demonstrate how to use the toJson() method.

<?php

namespace App\Http\Controllers;

use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Support\Collection;

class Controller extends BaseController
{
    use AuthorizesRequests, ValidatesRequests;


    public function index(){
        $collection = new Collection([
            ['name' =>  'iPhone 11 Pro', 'price'    =>  999],
            ['name' =>  'iPhone 11', 'price'    =>  799],
        ]);

        $jsonValue = $collection->toJson();
        dd($jsonValue);
    }
}

Output

After running the provided code, you will observe the following output for our $jsonValue variable.

"[{"name":"iPhone 11 Pro","price":999},{"name":"iPhone 11","price":799}]"

Example 2

To format the value for printing, simply use the option JSON_PRETTY_PRINT.

<?php

namespace App\Http\Controllers;

use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Support\Collection;

class Controller extends BaseController
{
    use AuthorizesRequests, ValidatesRequests;


    public function index(){
        $collection = new Collection([
            ['name' =>  'iPhone 11 Pro', 'price'    =>  999],
            ['name' =>  'iPhone 11', 'price'    =>  799],
        ]);


        $jsonValue = $collection->toJson(JSON_PRETTY_PRINT);
        dd($jsonValue);
    }
}

Output

[
    {
        "name": "iPhone 11 Pro",
        "price": 999
    },
    {
        "name": "iPhone 11",
        "price": 799
    }
]

toJson() and Deep Nested Data Structures

As I mentioned earlier, the toJson() method uses PHP's json_encode function internally. However, unlike PHP's json_encode method, toJson() doesn't allow you to specify the depth of the array for encoding, and it defaults to a depth of 512.

To convert a collection instance into its JSON with a depth exceeding 512, you can follow this approach.

use Illuminate\Support\Collection;

// Create a new collection instance.
$collection = new Collection([]);

// Replace 512 with the desired depth.
$jsonValue = json_encode(
    $collection->jsonSerialize(),
    0,
    512
);

That's it for today. I hope it'll be helpful in upcoming project. You can also download this source code from GitHub. Thanks for reading. ๐Ÿ™‚