Laravel 5 Message Bags: Adding Messages to the Message Bag With add

April 21, 2018 —John Koster

The add method adds a new message to the MessageBag instance. The message is identified by a given $key and contains the value $message. The add method returns a reference to the current MessageBag instance.

#Signature

The signature of the add method is:

1function function add(
2 $key,
3 $message
4);

#Example Use

The following code example demonstrates how to add messages to a MessageBag instance:

1use Illuminate\Support\MessageBag;
2 
3// Create a new MessageBag instance.
4$messageBag = new MessageBag;
5 
6// Add new messages to the message bag.
7$messageBag->add('hello', 'The first message bag message');
8$messageBag->add('world', 'The second message');
9 
10// Get an array of all the messages.
11$messages = $messageBag->getMessages();

After the above code has executed, the $messages variable will be an array and contain a value similar to the following output:

1array
2 'hello' =>
3 array
4 0 => string 'The first message bag message'
5 'world' =>
6 array
7 0 => string 'The second message'

The add method allows multiple messages to be stored under a given $key as long as the key/message pair is unique. As an example, another message can be supplied for the hello key like so:

1$messageBag->add('hello', 'This is a different hello');

And the output would then change to the following:

1array
2 'hello' =>
3 array
4 0 => string 'The first message bag message'
5 1 => string 'This is a different hello'
6 'world' =>
7 array
8 0 => string 'The second message'

#Notes on Keys

The $key supplied to the add method should make sense in some context. The examples so far have been fairly arbitrary, and are mainly designed to explain the concepts that are being presented. However, MessageBag instances are most commonly encountered during validation scenarios.

In cases like HTML form validation, the $key will generally be the name of the form element being validated. Assuming the following HTML form element:

{lang="html",line-numbers=on}

1<input type="text" name="username" />

Messages relating the username field could be stored like so:

1use Illuminate\Support\MessageBag;
2 
3// Create a new MessageBag instance.
4$errors = new MessageBag;
5 
6// Add example error messages to the MessageBag instance.
7$errors->add('username',
8 'The username field must longer than 5 characters');
9$errors->add('username',
10 'The username field must contain a special character');

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.