Skip to main content
Tutorial Free

str_plural(): Quickest way to show plural noun

March 14, 2016
1 min read
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.

Enjoyed This Tutorial?

Get access to all premium tutorials, video and text courses, and exclusive Laravel resources. Join our community of 10,000+ developers.

Comments & Discussion

A
AamirSohailKmAs ✓ Link copied!

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

We'd Love Your Feedback

Tell us what you like or what we can improve

Feel free to share anything you like or dislike about this page or the platform in general.