Laravel 5 Message Bags: Merging Additional Messages With merge

April 21, 2018 —John Koster

The merge method is used to combine, or merge, the contents of the MessageBag instance with the provided $messages. The $messages can be any valid array or an object instance that implements the "Illuminate\Contracts\Support\MessageProvider" interface. The merge method modifies the original MessageBag instance and returns a reference to the instance.

#Signature

The signature of the merge method is:

1public function merge(
2 $messages
3);

#Example Use

For example, the array:

1$arrayToMerge = [
2 'username' => [
3 'The username is required',
4 ],
5 'password' => [
6 'The passwords do not match',
7 ]
8];

can be merged with the following message bag:

1use Illuminate\Support\MessageBag;
2 
3// Create a new MessageBag instance.
4$messages = new MessageBag;
5$messages->add(
6 'username',
7 'That username has already been taken'
8);

like so:

1// Merge the $arrayToMerge with the $messages
2$messages->merge($arrayToMerge);
3 
4// Get the messages as an array.
5$messageArray = $messages->all();

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

1array (size=3)
2 0 => string 'That username has already been taken'
3 1 => string 'The username is required'
4 2 => string 'The passwords do not match'

Because the MessageBag class implements the MessageProvider interface, a MessageBag instance can be supplied as the argument for the $messages parameter:

1use Illuminate\Support\MessageBag;
2 
3// Create the first MessageBag instance.
4$firstMessageBag = new MessageBag([
5 'username' => 'The username is required'
6]);
7 
8// Create the second MessageBag instance.
9$secondMessageBag = new MessageBag([
10 'username' => 'That username has already been taken'
11]);
12 
13// Merge the two MessageBags.
14$firstMessageBag->merge($secondMessageBag);
15 
16// Get the messages as an array.
17$messageArray = $firstMessageBag->all();

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

1array
2 0 => string 'The username is required'
3 1 => string 'That username has already been taken'

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.