str_plural(): Quickest way to show plural noun

Laravel has a lot of helpers, for example to work with strings or arrays. One of them in particular helps with pluralization. Here’s what I mean.

Imagine a situation where you have to show text “X item(s)”, where if X > 1 then it’s “items”, otherwise “1 item”. How do we do that in Blade with simple IF?

{{ $items }} @if ($items > 1) items @else item @endif

Or a little shorter:

{{ $items }} item{{ ($items > 1) ? 's' : '' }}

But there’s even shorter way – with function str_plural():

{{ $items }} {{ str_plural('item', $items) }}

Function str_plural($noun, $count) has two parameters – it checks second parameter $count, and if its value is greater than 1 – it pluralizes the first parameter $noun.

Actually, second parameter is optional – so if you just want to show pluralize form of a noun, you can just do something like this:

{{ str_plural('child') }}

It would show ‘children’.

Any more useful helpers that are your favorites in Laravel? Let me know in the comments.

Like our articles?
Check out our Laravel online courses!



Please enter your comment!
Please enter your name here