Search

Laravel 5 View Error Bags: Add a New Message Bag Instance to the View Error Bag With put

April 21, 2018 —John Koster

The put method is used to add a new MessageBag implementation instance to the ViewErrorBag instance, supplied as the argument to the $bag parameter with some name determined by the $key argument.

#Signature

The signature of the put method is:

1public function put(
2 $key,
3 Illuminate\Contracts\Support\MessageBag $bag
4);

#Example Use

The following code demonstrates how to add a new MessageBag instance to a ViewErrorBag:

1use Illuminate\Support\ViewErrorBag;
2use Illuminate\Support\MessageBag;
3 
4// Create a new ViewErrorBag instance.
5$viewErrorBag = new ViewErrorBag;
6 
7// Create a new MessageBag instance.
8$messageBag = new MessageBag;
9 
10// Add the $messageBag to the $viewErrorBag
11// with some key.
12$viewErrorBag->put('somekey', $messageBag);
13 
14// Get the number of MessageBag instances.
15$messageBagCount = count($viewErrorBag->getBags());

After the above code has executed, the $messageBagCount variable would contain the value 1.

Another way to add MessageBag instances to the ViewErrorBag is by dynamically setting an instance property:

1// Add a new MessageBag instance without
2// using the 'put' method.
3$viewErrorBag->anotherKey = new MessageBag;

At this point, the $viewErrorBag instance would now contain two MessageBag instances with the keys somekey and anotherKey.

#Resetting MessageBag Messages

Because neither ViewErrorBag or MessageBag provide a method to quickly remove all the messages from a MessageBag instance, the put method can be used to remove all MessageBag messages, or supply new ones, by changing the MessageBag instance for a given key:

1// Create a different MessageBag instance.
2$newMessageBag = new MessageBag([
3 'username' => [
4 'The username is required.'
5 ]
6]);
7 
8// Get the 'somekey' MessageBag before changing it.
9$beforeChange = $viewErrorBag->getBag('somekey');
10 
11// Change the MessageBag instance.
12$viewErrorBag->put('somekey', $newMessageBag);
13 
14// Get the 'somekey' MessageBag after changing it.
15$afterChange = $viewErrorBag->getBag('somekey');

After the above code has executed, the $beforeChange variable would contain the old MessageBag instance and the $afterChange variable would contain the new MessageBag instance.

1object(Illuminate\Support\MessageBag)
2 protected 'messages' =>
3 array
4 empty
5 protected 'format' => string ':message'
1object(Illuminate\Support\MessageBag)
2 protected 'messages' =>
3 array
4 'username' =>
5 array
6 0 => string 'The username is required.'
7 protected 'format' => string ':message'

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.