Laravel comes packed with tons of handy string manipulation helpers. Among them, Str::plural() and Str::singular() are super useful when you need to follow Laravel’s naming conventions for database tables and models!

Today, I’ll show you how to use these methods and share some practical examples ✨

Basic Usage

Str::plural() – Converting to Plural Form

Converts singular English words to their plural forms.

use IlluminateSupportStr; // Basic examples Str::plural('user'); // users Str::plural('person'); // people Str::plural('child'); // children Str::plural('ox'); // oxen 

Str::singular() – Converting to Singular Form

Converts plural English words to their singular forms.

Str::singular('users'); // user Str::singular('people'); // person Str::singular('children'); // child Str::singular('oxen'); // ox 

Practical Examples

1. Dynamic Table Name Generation

$modelName = 'User'; $tableName = Str::plural(Str::snake($modelName)); // Returns 'users' 

2. Dynamic Message Generation

$count = 5; $item = 'item'; $message = "You have {$count} " . Str::plural($item, $count); // "You have 5 items" 

Live Demo

I’ve created a demo page where you can try it out!

🔗 Singular/Plural Conversion Sample

On this page, you can test singular/plural conversion with various English words.

Specifically, the Controller handles the conversion like this:

$word = $request->input('word'); $singular = IlluminateSupportStr::singular($word); $plural = IlluminateSupportStr::plural($word); 

Since it’s deployed on Render, the first access might take a bit longer to load.

Important Notes

  • These methods cover basic English pluralization rules, but they don’t handle all irregular forms
  • For more complex conversions, consider using the IlluminateSupportPluralizer class directly
  • If you need custom rules, you can register your own conversion rules in a service provider

Conclusion

Str::plural() and Str::singular() are incredibly useful helper methods when developing with Laravel’s conventions. Try using them when dynamically generating table names or messages!

Feel free to try out various words on the demo page! ♪


Source: DEV Community.


Leave a Reply

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

The reCAPTCHA verification period has expired. Please reload the page.