DEV Community

yone3
yone3

Posted on

Hey Laravel users — are you using Plural / Singular!?

Introduction

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 Illuminate\Support\Str;

// Basic examples
Str::plural('user');     // users
Str::plural('person');   // people
Str::plural('child');    // children
Str::plural('ox');       // oxen
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Practical Examples

1. Dynamic Table Name Generation

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

2. Dynamic Message Generation

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

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 = \Illuminate\Support\Str::singular($word);
$plural = \Illuminate\Support\Str::plural($word);
Enter fullscreen mode Exit fullscreen mode

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 Illuminate\Support\Pluralizer 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! ♪

Top comments (0)