Laravel Plural Strings Based on the Count
Hello Artisans, today I'll show you how we can show the string in singular/plural form based on the count of an item/items. Suppose, we're working on an ecommerce project, and there is a cart system where we've to show how many item/items user added to his cart. But one thing, you should notice item/items, which is come by the count of product/item user added to his cart. So, today's tutorial was about how we can easily show the singular/plural form of a string based on the item count in our Laravel Application.
Note: Tested on Laravel 9.19.
plural() helper method
We can easily pluralize the any word using the plural() helper method of Str::class. See the below code snippet for more info.
<?php use Illuminate\Support\Str; $itemCount = 1; $cartItems = Str::of('item')->plural($itemCount); // it'll print item $itemCount = 10; $cartItems = Str::of('item')->plural($itemCount); // it'll print items
Not only that we can use it for complex strings which plural forms are somewhat unconventional. Like if we see the below code snippet we can understand better.
<?php use Illuminate\Support\Str; $plural = Str::of('child')->plural(5); //it'll print children
Hope you understand what a simple and useful method it is. Hope you'll be helpful using this method.
That's it for today. Hope you've enjoyed this tutorial. Thanks for reading. 🙂