Laravel MessageBag Public API: merge

November 29, 2016 —John Koster

merge($messages)

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.

For example, the array:

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

can be merged with the following message bag:

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

like so:

1<?php
2 
3// Merge the $arrayToMerge with the $messages
4$messages->merge($arrayToMerge);
5 
6// Get the messages as an array.
7$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' (length=36)
3 1 => string 'The username is required' (length=24)
4 2 => string 'The passwords do not match' (length=26)

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

1<?php
2 
3use Illuminate\Support\MessageBag;
4 
5// Create the first MessageBag instance.
6$firstMessageBag = new MessageBag([
7 'username' => 'The username is required'
8]);
9 
10// Create the second MessageBag instance.
11$secondMessageBag = new MessageBag([
12 'username' => 'That username has already been taken'
13]);
14 
15// Merge the two MessageBags.
16$firstMessageBag->merge($secondMessageBag);
17 
18// Get the messages as an array.
19$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 (size=2)
2 0 => string 'The username is required' (length=24)
3 1 => string 'That username has already been taken' (length=36)

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