Black Friday: coupon FRIDAY24 for 40% off Yearly/Lifetime membership! Read more here

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

str_plural only support english language, If someone is looking for diffenent Langauge then check official documentation, Pluralization

👍 1

Like our articles?

Become a Premium Member for $129/year or $29/month
What else you will get:
  • 67 courses (1172 lessons, total 43 h 18 min)
  • 90 long-form tutorials (one new every week)
  • access to project repositories
  • access to private Discord

Recent New Courses