Published in Laravel

Laravel MessageBag Public API: __toString

By 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: