Search

Laravel MessageBag Public API: toJson

November 29, 2016 —John Koster

toJson($options = 0)

The toJson method will return a JSON encoded version of the data stored within the message bag 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 
3use Illuminate\Support\MessageBag;
4 
5// Create a new MessageBag instance.
6$messageBag = new MessageBag;
7 
8// Add items to the MessageBag
9$messageBag->add('first', 'The very first message');
10$messageBag->add('first', 'The second message');
11$messageBag->add('second', 'I should not be in the output');
12 
13// Convert the MessageBag to JSON.
14$jsonValue = $messageBag->toJson();

After the above code has executed, the $jsonValue variable would contain a value similar to the following output (some lines have been wrapped and indented to improve readability):

1string '{"first":["The very first message","The second message"],
2 "second":["I should not be in the output"]}' (length=100)

Alternatively, a well-formatted value can be returned by passing in the JSON_PRETTY_PRINT constant:

1<?php
2 
3// Convert the MessageBag to formatted JSON.
4$jsonValue = $messageBag->toJson(JSON_PRETTY_PRINT);

After the above code has executed, the $jsonValue variable would now contain formatted JSON, similar to the following output:

1{
2 "first": [
3 "The very first message",
4 "The second message"
5 ],
6 "second": [
7 "I should not be in the output"
8 ]
9}

#toJson and Deeply Nested Data Structures

The 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 message bag instance into its JSON equivalent with a depth greater than 512, the following method will be sufficient:

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

#Continue Reading

This article is the start of a mini-series about Laravel's ErrorMessageBag component. Click through the rest of the articles to continue reading:

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.