Laravel MessageBag Public API: add

November 29, 2016 —John Koster

add($key, $message)

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.

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

1<?php
2 
3use Illuminate\Support\MessageBag;
4 
5// Create a new MessageBag instance.
6$messageBag = new MessageBag;
7 
8// Add new messages to the message bag.
9$messageBag->add('hello', 'The first message bag message');
10$messageBag->add('world', 'The second message');
11 
12// Get an array of all the messages.
13$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 (size=2)
2 'hello' =>
3 array (size=1)
4 0 => string 'The first message bag message' (length=29)
5 'world' =>
6 array (size=1)
7 0 => string 'The second message' (length=18)

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<?php
2 
3$messageBag->add('hello', 'This is a different hello');

And the output would then change to the following:

1array (size=2)
2 'hello' =>
3 array (size=2)
4 0 => string 'The first message bag message' (length=29)
5 1 => string 'This is a different hello' (length=25)
6 'world' =>
7 array (size=1)
8 0 => string 'The second message' (length=18)

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

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

Messages relating the username field could be stored like so:

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

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