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.
The signature of the count
method is:
1public function count();
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 to15// the ViewErrorBag16$viewErrorBag->put('formErrors', $messageBag);17 18// Get the count from $viewErrorBag19//20// 021$messageCount = $viewErrorBag->count();22 23// Change the 'default' MessageBag to the one24// created earlier.25$viewErrorBag->put('default', $messageBag);26 27// Get the count from $viewErrorBag28//29// 130$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.
∎
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.