Search

Laravel 5: Getting Specific Messages With get

April 21, 2018 —John Koster

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.

#Signature

The signature of the get method is:

1public function get(
2 $key,
3 $format = null
4);

#Example Use

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

1// Create a new MessageBag instance.
2$messageBag = new MessageBag;
3 
4// Add items to the MessageBag
5$messageBag->add('first', 'The very first message');
6$messageBag->add('first', 'The second message');
7$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
1$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
2 0 => string 'The message was: The very first message'
3 1 => string 'The message was: The second 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.