Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Inflector Laravel Package

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.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation Add the package via Composer:

    composer require symfony/inflector
    

    No additional configuration is required—it’s a standalone library.

  2. 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"
    
  3. Where to Look First


Implementation Patterns

Core Workflows

  1. Model/Table Naming Dynamically generate pluralized table names for Eloquent models:

    $modelName = 'User';
    $tableName = Inflector::tableize($modelName); // "users"
    
  2. URL/Route Slugs Convert snake_case to human-readable strings:

    $slug = Inflector::humanize('user_profile'); // "User Profile"
    
  3. Form Labels & Placeholders Auto-generate user-friendly labels from database columns:

    $label = Inflector::classify('first_name'); // "FirstName"
    $placeholder = Inflector::humanize($label);  // "First name"
    
  4. Batch Processing Apply transformations to arrays of strings:

    $words = ['mouse', 'box', 'goose'];
    $pluralized = array_map([Inflector::class, 'pluralize'], $words);
    // ["mice", "boxes", "geese"]
    

Integration Tips

  • 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);
        }
    }
    

Gotchas and Tips

Pitfalls

  1. 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.

  2. 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');
    
  3. 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.

  4. 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');
    

Debugging

  • 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")
    

Extension Points

  1. 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);
        }
    }
    
  2. 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.

  3. 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);
        }
    }
    

Pro Tips

  • 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;
        });
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor
spatie/laravel-javascript-views