Laravel ViewErrorBag Public API: put

November 29, 2016 —John Koster

put($key, Illuminate\Contracts\Support\MessageBag $bag)

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. The following code demonstrates how to add a new MessageBag instance to a ViewErrorBag:

1<?php
2 
3use Illuminate\Support\ViewErrorBag;
4use Illuminate\Support\MessageBag;
5 
6// Create a new ViewErrorBag instance.
7$viewErrorBag = new ViewErrorBag;
8 
9// Create a new MessageBag instance.
10$messageBag = new MessageBag;
11 
12// Add the $messageBag to the $viewErrorBag
13// with some key.
14$viewErrorBag->put('somekey', $messageBag);
15 
16// Get the number of MessageBag instances.
17$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<?php
2 
3// Add a new MessageBag instance without
4// using the 'put' method.
5$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<?php
2 
3// Create a different MessageBag instance.
4$newMessageBag = new MessageBag([
5 'username' => [
6 'The username is required.'
7 ]
8]);
9 
10// Get the 'somekey' MessageBag before changing it.
11$beforeChange = $viewErrorBag->getBag('somekey');
12 
13// Change the MessageBag instance.
14$viewErrorBag->put('somekey', $newMessageBag);
15 
16// Get the 'somekey' MessageBag after changing it.
17$afterChange = $viewErrorBag->getBag('somekey');

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

1object(Illuminate\Support\MessageBag)[142]
2 protected 'messages' =>
3 array (size=0)
4 empty
5 protected 'format' => string ':message' (length=8)
1object(Illuminate\Support\MessageBag)[143]
2 protected 'messages' =>
3 array (size=1)
4 'username' =>
5 array (size=1)
6 0 => string 'The username is required.' (length=25)
7 protected 'format' => string ':message' (length=8)

#Continue Reading

This article is part of a mini-series all about Laravel's View Error Bags. Each of these articles can be found here:

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.