Search

Laravel ViewErrorBag Public API: count

November 29, 2016 —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.

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

#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.