Laravel 5 Message Bags: Converting the Message Bag to JSON With toJson

April 21, 2018 —John Koster

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.

#Signature

The signature of the toJson method is:

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

#Example Use

The following examples demonstrate the basic usage of the toJson method:

1use Illuminate\Support\MessageBag;
2 
3// Create a new MessageBag instance.
4$messageBag = new MessageBag;
5 
6// Add items to the MessageBag
7$messageBag->add('first', 'The very first message');
8$messageBag->add('first', 'The second message');
9$messageBag->add('second', 'I should not be in the output');
10 
11// Convert the MessageBag to JSON.
12$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 '{
2 "first": [
3 "The very first message",
4 "The second message"
5 ],
6 "second": [
7 "I should not be in the output"
8 ]
9}'

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

1// Convert the MessageBag to formatted JSON.
2$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:

1use Illuminate\Support\MessageBag;
2 
3// Create a new MessageBag instance.
4$messageBag = new MessageBag([]);
5 
6// Replace 512 with the desired depth.
7$jsonValue = json_encode(
8 $messageBag->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.