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. 🙂
Preview may take a few seconds to load.
Below you will find some common used markdown syntax. For a deeper dive in Markdown check out this Cheat Sheet
Bold & Italic
Bold **double asterisks**
Three back ticks and then enter your code blocks here.
# This is a Heading 1
## This is a Heading 2
### This is a Heading 3
> type a greater than sign and start typing your quote.
You can add links by adding text inside of  and the link inside of (), like so:
To add a numbered list you can simply start with a number and a ., like so:
1. The first item in my list
For an unordered list, you can add a dash -, like so:
- The start of my list
You can add images by selecting the image icon, which will upload and add an image to the editor, or you can manually add the image by adding an exclamation !, followed by the alt text inside of , and the image URL inside of (), like so:
To add a divider you can add three dashes or three asterisks:
--- or ***