Automatic pluralization with str_plural() helper


Committed to the LaraBrain by: neovive (@neovive) at November 11, 2015 4:15 pm

Keep your views clean with automatic pluralization using the str_plural() helper

Most web developers have encountered a time when they needed to pluralize a noun in their view. For example, let's say you are building a shopping cart and customer can add one or more widgets to their cart. Your checkout screen offers a friendly reminder about how many widgets are in the cart.

But, how do you determine whether to write widgets or widget? Do we clutter our view with @if ($cart->quantity()) > 1 ... ? Do we take the easy way and just write widget(s)? Nope--we can do better and Laravel makes it easy using the helper in your blade view as follows:

{{ str_plural('widget', $cart->quantity()) }}