Laravel MessageBag Public API: get

November 29, 2016 —John Koster

get($key, $format = null)

The get method can be used to retrieve all the messages for a given $key with the specified $format. The $format is null by default, which will cause the get method to use the format stored within the MessageBag instance (which can be retrieved using the getFormat method). Alternatively, developers can specify their own $format to customize the results each time the get method is executed. The get method will return an array containing all of the formatted messages.

The following example code will create a new MessageBag instance that can be used to retrieve messages from:

3// Create a new MessageBag instance.
4$messageBag = new MessageBag;
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');

The following code will retrieve all of the messages with the given format:

1The message was: :message
3$messages = $messageBag->get('first', 'The message was: message');

After the above code has executed, the $messages variable will be an array and contain a value similar to the following output. It can be seen that the output only contains the messages related to the first key:

1array (size=2)
2 0 => string 'The message was: The very first message' (length=39)
3 1 => string 'The message was: The second message' (length=35)

#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

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.