Search

Laravel 5 View Error Bags: Getting the Number of Error Messages With count

April 21, 2018 —John Koster

The count method returns the number of messages stored within the default MessageBag instance. It is also the only MessageBag method that specifically handled by the ViewErrorBag instance itself because it needs to be declared within the ViewErrorBag class itself to satisfy the requirements of PHP's Countable interface.

#Signature

The signature of the count method is:

1public function count();

#Example Use

The following code example demonstrates the behavior of the count 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 the new MessageBag instance to
15// the ViewErrorBag
16$viewErrorBag->put('formErrors', $messageBag);
17 
18// Get the count from $viewErrorBag
19//
20// 0
21$messageCount = $viewErrorBag->count();
22 
23// Change the 'default' MessageBag to the one
24// created earlier.
25$viewErrorBag->put('default', $messageBag);
26 
27// Get the count from $viewErrorBag
28//
29// 1
30$messageCount = count($viewErrorBag);

As can be seen in the comments in the above example, the count method only operates on the default MessageBag instance. Because of this adding the MessageBag formErrors did not affect the count, but setting the same MessageBag instance as the value for the default key did change the results of the count method.

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.