November 29, 2016 —John Koster
getBag($key = null)
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.
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 'username' => [12 'The username is required.'13 ]14]);15 16$viewErrorBag->put('formErrors', $messageBag);17 18// Demonstrate that the object returned by the getBag19// method is the same as $messageBag.20//21// true22$areTheSame = $messageBag === $viewErrorBag->getBag('formErrors');
Additionally, you can request a MessageBag
instance with any $key
, even if they have not been set:
1<?php2 3// Request a MessageBag that has not been set yet.4$messageBagInstance = $viewErrorBag->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<?php 2 3$messageBagInstance = $viewErrorBag->getBag('paymentErrors'); 4 5// Add a message to the $messageBagInstance 6$messageBagInstance->add('ccn', 'The credit card number is invalid'); 7 8// Get the number of messages. 9//10// 111$messageCount = $messageBagInstance->count();12 13// Get the number of messages.14//15// 016$messageCount = $viewErrorBag->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<?php2 3// Get the 'formErrors' MessageBag instance.4$formErrors = $viewErrorBag->formErrors;
This article is part of a mini-series all about Laravel's View Error Bags. Each of these articles can be found here:
∎
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.