Laravel Collection – Using toJson() Method

Laravel Collection - Using toJson Method

Laravel Collections ( 10 Lessons )

Laravel Collections is one of the most powerful features of Laravel. Basically, collections are PHP arrays but it’s an Object Oriented approach to deal with PHP arrays.

see full series
  1. Laravel Collections – Introduction to Collections
  2. Laravel Collections – make Method
  3. Laravel Collections – wrap() and unwrap() Methods
  4. Laravel Collections – map() Method
  5. Laravel Collections – times() Method
  6. Laravel Collections – collapse() Method
  7. Laravel Collections – contains() & containsStrict() Methods
  8. Laravel Collections – each() Method
  9. Laravel Collection – Using toJson() Method
  10. Laravel Collection – Filtering Collection Items using where()

Laravel Collection provides an easy interface to work with the PHP array. Today, we will be looking at how we can use the toJson() method to convert a Laravel Collection to JSON format.

The toJson() method will return the JSON encoded version of the data stored in a Laravel Collection. Under the hood Laravel, apply the native json_encode() method of PHP. This method takes one optional argument $options. Like the json_encode function, the $options parameter is a bitmask of the predefined JSON constants.

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

In the below example, we can see how toJson() method can be used.

// Create a new collection for our example
$collection = new Collection([
    ['name' =>  'iPhone 11 Pro', 'price'    =>  999],
    ['name' =>  'iPhone 11', 'price'    =>  799],
]);

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

After you execute the above code, you will find the below output for our $jsonValue variable.

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

To print the formatted value, we can pass the JSON_PRETTY_PRINT contant as a option.

// Create a new collection for our example
$collection = new Collection([
    ['name' =>  'iPhone 11 Pro', 'price'    =>  999],
    ['name' =>  'iPhone 11', 'price'    =>  799],
]);

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

Now if you print the value of $jsonValue, you will get the output something like below.

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

toJson() and Deep Nested Data Structures

As I mentioned above that toJson() method makes call to native PHP function json_encode. Unlike the PHP’s json_encode method, the toJson() method does not provide the way to specify the depth of the array to which data will be encoded which is by default set to 512.

To convert a collection instance into its JSON with depth greater than 512, you can take the following 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
);

Leave a Reply

Your email address will not be published. Required fields are marked *

*

When sharing a code snippet please wrap you code with pre tag and add a class code-block to it like below.
<pre class="code-block">you code here</pre>

*
*

This site uses Akismet to reduce spam. Learn how your comment data is processed.