Laravel 5 Message Bags: Retrieving the First Message With first

April 21, 2018 —John Koster

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

#Signature

The signature of the first method is:

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

#Example Use

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:

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

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

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

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.