Laravel MessageBag Public API: __toString

November 29, 2016 —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.

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

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

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

#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.