Laravel 5 Message Bags: Converting the Message Bag to Something JSON Serializable With jsonSerialize

April 21, 2018 —John Koster

The jsonSeralize method internally returns the value of the toArray method. This method exists to implement PHP's JsonSerializable interface, which allows developers to customize how a class is represented when using the json_encode function.


The signature of the jsonSerialize method is:

1public function jsonSerialize();

#Example Use

The following example demonstrates the jsonSerialize method:

1use Illuminate\Support\MessageBag;
3// Create a new MessageBag instance.
4$messageBag = new MessageBag;
6// Add new messages to the message bag.
7$messageBag->add('hello', 'The first message bag message');
8$messageBag->add('world', 'The second message');
10// Get a value that can be converted to JSON.
11$messages = $messageBag->jsonSerialize();

After the above code has executed, the $messages variable will be an array and contain a value similar to the following output:

2 'hello' =>
3 array
4 0 => string 'The first message bag message'
5 'world' =>
6 array
7 0 => string 'The second message'

Some absolutely amazing

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.