Array to JSON with toJson() Method

toJson() is one of the most helpful and commonly used methods in Laravel. In simple concept, toJson() returns the JSON-encoded data version of the Laravel array or collection. This method takes one optional parameter i.e. $options.

This method is very similar to json_encode() in PHP.

Structure

toJson() is located in Illuminate/Support/Collection. Its structure is like this:

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

Let’s Practice Array to JSON Conversion

First, lets talk about how we can use toJson() method.

// Create a new collection
$collection = new Collection([
    ['name' =>  'PS5', 'price'    =>  899],
    ['name' =>  'PS2', 'price'    =>  199],
]);

// Convert the collection to JSON format
$jsonValue = $collection->toJson();

As shown in the above example, first of all, an array is declared which is later converted in JSON. The result of the above example looks like this:

[{"name":"PS5","price":899},{"name":"PS2","price":199}]

For printing the formatted value, we can pass JSON_PRETTY_PRINT as parameter:

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

After that, if we print the variable we will get result something like this:

[
    {
        "name": "PS5",
        "price": 899
    },
    {
        "name": "PS2",
        "price": 199
    }
]

Nested Data Structure and toJson()

Specification of the depth of the array to which data will be encoded is not provided by the toJson() method. It is set to 512 by default. But if the user wants to go deeper than 512 then the user can take 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
);

These are all the basics of toJson() method. Hope you enjoyed this tutorial;)

For more tutorials click here

Asmit Nepali, a Full Stack Developer, holds a Software Engineering degree from Gandaki College of Engineering and Science. Proficient in PHP Laravel, Vue.js, MySQL, Tailwind, Figma, and Git, he possesses a robust technical skill set.

Leave a Comment