Laravel MessageBag Public API: first

November 29, 2016 —John Koster

first($key = null, $format = null)

The first method will return the first message in the MessageBag instance for a given $key. If the $key is null the first method will return the first message in the MessageBag instance. If there are no messages stored within the message bag, the first method will return an empty string. The first method also accepts a $format parameter, which allows developers to customize the format that is used when transforming the message (which by default is just the default message).

The following examples will demonstrate the usage of the first method. The result of the method call will appear above the method call as a comment:

3use Illuminate\Support\MessageBag;
5// Create a new MessageBag instance.
6$messageBag = new MessageBag;
7$messageBag->add('first', 'This is a message');
8$messageBag->add('first', 'I am also a message -.- ');
9$messageBag->add('second', 'Can I join, too?');
11// 'This is a message'
12$message = $messageBag->first();
14// 'Can I join, too?'
15$message = $messageBag->first('second');
17// '' (an empty string)
18$message = $messageBag->first('does_not_exist');

The following example also changes the format of the returned message:

3// <li>This is a message</li>
4$message = $messageBag->first('first', '<li>:message</li>');

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