Laravel 5 Collections: Converting a Collection's Contents to JSON With toJson

April 22, 2018 —John Koster

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.

#Signature

1public function toJson(
2 $options = 0
3);

#Example Use

The following code examples demonstrate the basic use of the toJson method:

1// Create a new collection instance.
2$collection = new Collection([
3 ['name' => 'Shirley', 'age' => 60],
4 ['name' => 'John', 'age' => 55]
5]);
6 
7// Convert the collection to JSON.
8$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// Create a new collection instance.
2$collection = new Collection([
3 ['name' => 'Shirley', 'age' => 60],
4 ['name' => 'John', 'age' => 55]
5]);
6 
7// Convert the collection to JSON.
8$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 Structures

The toJson method internally makes a call to PHP's json_encode function. Unlike PHP's json_encode function, the toJson method 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 approach will be sufficient:

1use Illuminate\Support\Collection;
2 
3// Create a new collection instance.
4$collection = new Collection([]);
5 
6// Replace 512 with the desired depth.
7$jsonValue = json_encode(
8 $collection->jsonSerialize(),
9 0,
10 512
11 );

Some absolutely amazing
people

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.