Laravel 5 View Error Bags: Getting the Message Bag Instance With getBag

April 21, 2018 —John Koster

The getBag method can be used to retrieve a MessageBag instance associated with the provided $key. If a MessageBag instance does not exist with the provided $key, a new instance of "Illuminate\Support\MessageBag" will returned instead.

The following code sample will demonstrate the usage of the getBag method. It also shows that because of the way PHP internally handles objects and references, that the $messageBag is the same as the value returned from the getBag method.

#Signature

The signature of the getBag method is:

1public function getBag(
2 $key
3);

#Example Use

The following example demonstrates the usage of the getBag method:

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 'username' => [
10 'The username is required.'
11 ]
12]);
13 
14$viewErrorBag->put('formErrors', $messageBag);
15 
16// Demonstrate that the object returned by the getBag
17// method is the same as $messageBag.
18//
19// true
20$areTheSame = $messageBag === $viewErrorBag
21 ->getBag('formErrors');

Additionally, you can request a MessageBag instance with any $key, even if they have not been set:

1// Request a MessageBag that has not been set yet.
2$messageBagInstance = $viewErrorBag
3 ->getBag('paymentErrors');

It should be noted that the getBag method does not set the MessageBag instance that is returning. This behavior can lead to some confusion, and can be observed in the following code sample:

1$messageBagInstance = $viewErrorBag
2 ->getBag('paymentErrors');
3 
4// Add a message to the $messageBagInstance
5$messageBagInstance->add(
6 'ccn',
7 'The credit card number is invalid'
8);
9 
10// Get the number of messages.
11//
12// 1
13$messageCount = $messageBagInstance->count();
14 
15// Get the number of messages.
16//
17// 0
18$messageCount = $viewErrorBag
19 ->getBag('paymentErrors')->count();

If the ViewErrorBag instance had set the MessageBag instance before returning it from the getBag method, both $messageCount variables would have contained the value 1.

Another way to retrieve MessageBag instances from the ViewErrorBag instance is dynamically access a property, where the property name is the intended key. This technique exhibits the same behavior as using the getBag method.

1// Get the 'formErrors' MessageBag instance.
2$formErrors = $viewErrorBag->formErrors;

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.