Laravel 5 View Error Bags: Getting all Message Bag Instances With getBags

April 21, 2018 —John Koster

The getBags method is used to return an associative array containing all the MessageBag instances that are currently stored within the ViewErrorBag instance.

#Signature

The signature of the getBags method is:

1public function getBags();

#Example Use

The following example demonstrates the basic usage of the getBags 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// Add some message bags to $viewErrorBag
15$viewErrorBag->put('formErrors', $messageBag);
16$viewErrorBag->put('paymentErrors', new MessageBag);
17 
18// Get the message bags as an array.
19$messageBags = $viewErrorBag->getBags();

After the above code has executed, the $messageBags variable would be an array and contain a value similar to the following output:

1array
2 'formErrors' =>
3 object(Illuminate\Support\MessageBag)
4 protected 'messages' =>
5 array
6 'username' =>
7 array
8 ...
9 protected 'format' => string ':message'
10 'paymentErrors' =>
11 object(Illuminate\Support\MessageBag)
12 protected 'messages' =>
13 array
14 empty
15 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.