symfony/inflector
Deprecated since Symfony 5.1. Symfony Inflector converts English words between singular and plural forms. Use the String component’s EnglishInflector instead. Issues and PRs should be filed in the main Symfony repository.
Installation Add the package via Composer:
composer require symfony/inflector
No additional configuration is required—it’s a standalone library.
First Use Case
Import the Inflector class and use its static methods:
use Symfony\Component\String\Inflector\Inflector;
// Convert singular to plural
$plural = Inflector::pluralize('child'); // "children"
// Convert plural to singular
$singular = Inflector::singularize('children'); // "child"
// Convert to title case
$title = Inflector::titlecase('hello_world'); // "Hello World"
Where to Look First
src/Inflector.php (simple, no magic).Tests/InflectorTest.php for edge cases.Model/Table Naming Dynamically generate pluralized table names for Eloquent models:
$modelName = 'User';
$tableName = Inflector::tableize($modelName); // "users"
URL/Route Slugs Convert snake_case to human-readable strings:
$slug = Inflector::humanize('user_profile'); // "User Profile"
Form Labels & Placeholders Auto-generate user-friendly labels from database columns:
$label = Inflector::classify('first_name'); // "FirstName"
$placeholder = Inflector::humanize($label); // "First name"
Batch Processing Apply transformations to arrays of strings:
$words = ['mouse', 'box', 'goose'];
$pluralized = array_map([Inflector::class, 'pluralize'], $words);
// ["mice", "boxes", "geese"]
Laravel Service Provider
Bind Inflector as a singleton for global access:
use Symfony\Component\String\Inflector\Inflector;
public function register()
{
$this->app->singleton('inflector', function () {
return new Inflector();
});
}
Then inject it into controllers/services:
use Illuminate\Support\Facades\App;
$plural = App::make('inflector')->pluralize('child');
Blade Directives Create a custom Blade directive for reusable transformations:
Blade::directive('pluralize', function ($expression) {
return "<?php echo \\Symfony\\Component\\String\\Inflector\\Inflector::pluralize({$expression}); ?>";
});
Usage:
@pluralize('user') <!-- Outputs "users" -->
Model Observers Auto-pluralize related model names in observers:
public function saving(Model $model)
{
if ($model->relation_name === 'posts') {
$model->relation_name = Inflector::singularize($model->relation_name);
}
}
Non-English Words
The package is English-only. Inputs like "maus" (German) may return incorrect results ("mauses" instead of "mäuse").
Workaround: Pre-process or validate input for non-English terms.
Irregular Plurals
Some words (e.g., "ox" → "oxen", "person" → "people") require manual overrides.
Workaround: Use Inflector::setIrregularRule() or extend the class:
Inflector::setIrregularRule('ox', 'oxen');
Edge Cases in classify()
Inflector::classify('user_id') returns "UserId" (camelCase), but Inflector::classify('user_id', true) returns "UserID" (PascalCase with underscores).
Tip: Always specify the second argument (true for PascalCase) for consistency.
Performance in Loops
Avoid instantiating Inflector repeatedly. Cache the instance or use static methods:
// Bad (creates new instance each call)
$inflector = new Inflector();
$inflector->pluralize('child');
// Good (static)
Inflector::pluralize('child');
Unexpected Output? Check the test cases for expected behavior. Example:
Inflector::pluralize('child') // "children" (correct)
Inflector::pluralize('childs') // "childs" (incorrect, but no override)
Custom Rules Not Applying? Verify rules are set before use:
Inflector::setIrregularRule('news', 'news'); // Must run first
Inflector::pluralize('news'); // "news" (not "newses")
Override Default Rules Extend the class to add custom logic:
class CustomInflector extends Inflector
{
public static function pluralize($word)
{
if ($word === 'custom_word') {
return 'custom_words';
}
return parent::pluralize($word);
}
}
Add Custom Rules via Config
Load rules from a config file (e.g., config/inflector.php):
'irregular_rules' => [
'custom' => 'customs',
'alias' => 'aliases',
],
Then apply them in a service provider’s boot() method.
Localization
For non-English support, wrap Inflector in a facade with language-specific logic:
class LocalizedInflector
{
public static function pluralize($word, $locale = 'en')
{
if ($locale === 'de') {
return Str::of($word)->replace('s', 'se'); // German hack
}
return Inflector::pluralize($word);
}
}
Combine with Laravel Helpers
Pair with Str::of() for chained transformations:
$title = Str::of('user_profile')
->replace('_', ' ')
->title();
// "User Profile"
Database Schema Generation Auto-generate migration table names:
$tableName = Inflector::tableize(class_basename($model));
Schema::create($tableName, function (Blueprint $table) { ... });
API Response Formatting Normalize JSON keys for consistency:
$response['data'] = collect($response['data'])
->map(function ($item) {
$item['id'] = Inflector::singularize($item['id']);
return $item;
});
How can I help you explore Laravel packages today?