Laravel 5 Message Bags: Converting a Message Bag to a String with __toString

April 21, 2018 —John Koster

When a MessageBag instance is cast into a string, its JSON representation is returned as the result. Internally this is accomplished by returning the result of the toJson method.

#Signature

The signature of the __toString magic method is:

1public function __toString();

#Example Use

The following example demonstrates how to cast a message bag instance to a string:

1use Illuminate\Support\MessageBag;
2 
3// Create a new MessageBag instance.
4$messageBag = new MessageBag([
5 'first' => ['The first message']
6]);
7 
8// Cast the MessageBag into a string.
9$stringValue = (string) $messageBag;

After the above code executes, the $stringValue variable would contain the following value:

1{"first": ["The first message" ]}

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.