November 30, 2016 —John Koster
toJson($options = 0)
The toJson
method will return a JSON encoded version of the data stored within the collection instance. It internally does this by returning a call to PHP's json_encode
function, passing in any $options
that were supplied. Like the json_encode
function, the $options
parameter is a bitmask of the predefined JSON constants.
1<?php 2 3// Create a new collection instance. 4$collection = new Collection([ 5 ['name' => 'Shirley', 'age' => 60], 6 ['name' => 'John', 'age' => 55] 7]); 8 9// Convert the collection to JSON.10$jsonValue = $collection->toJson();
After the above code executes, $jsonValue
would contain the following value:
1[{"name":"Shirley","age":60},{"name":"John","age":55}]
Alternatively, a well-formatted value can be returned by passing in the JSON_PRETTY_PRINT
constant:
1<?php 2 3// Create a new collection instance. 4$collection = new Collection([ 5 ['name' => 'Shirley', 'age' => 60], 6 ['name' => 'John', 'age' => 55] 7]); 8 9// Convert the collection to JSON.10$jsonValue = $collection->toJson(JSON_PRETTY_PRINT);
This time, the $jsonValue
would contain the following value:
1[ 2 { 3 "name": "Shirley", 4 "age": 60 5 }, 6 { 7 "name": "John", 8 "age": 55 9 }10]
toJson
and Deeply Nested Data StructuresThe toJson
method internally makes a call to PHP's json_encode
function. Unlike json_encode
, toJson
does not provide a way to specify the depth (essentially how many arrays are nested inside of each other) to which data will be encoded, which is by default set to 512
. To convert a collection instance into its JSON equivalent with a depth greater than 512
, the following method will be sufficient:
1<?php2 3use Illuminate\Support\Collection;4 5// Create a new collection instance.6$collection = new Collection([]);7 8// Replace 512 with the desired depth.9$jsonValue = json_encode($collection->jsonSerialize(), 0, 512);
∎
The following amazing people help support this site and my open source projects ♥️
If you're interesting in supporting my work and want to show up on this list, check out my GitHub Sponsors Profile.