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

Inflect Laravel Package

oodle/inflect

Lightweight PHP inflector for converting English words between singular and plural forms. Install via Composer and use static methods like Inflect::singularize('tests') and Inflect::pluralize('test') for quick string inflection.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add to composer.json:

    "require": {
        "oodle/inflect": "^1.0"
    }
    

    Run composer update or composer install.

  2. First Usage Import and use the Inflect facade in your Laravel app:

    use Inflect\Inflect;
    
    // Basic inflection
    $singular = Inflect::singularize('photos'); // "photo"
    $plural   = Inflect::pluralize('child');    // "children"
    
  3. First Use Case Dynamically generate model names or table names in controllers/views:

    $modelName = Inflect::singularize(request()->route()->getName());
    $tableName = Inflect::tableize($modelName); // e.g., "posts" → "post" → "posts"
    

Implementation Patterns

Core Workflows

  1. Model/Table Name Generation Use Inflect to auto-generate Eloquent model/table names from routes or user input:

    $routeName = 'admin/users/posts';
    $modelName = Inflect::singularize($routeName); // "post"
    $tableName = Inflect::tableize($modelName);    // "posts"
    
  2. Dynamic Form Labels Convert snake_case or pluralized fields to human-readable labels:

    $field = 'user_posts_count';
    $label = Inflect::humanize($field); // "User posts count"
    
  3. Memoization for Performance Leverage memoization for repeated inflections (e.g., in loops or API responses):

    // First call caches the result
    Inflect::pluralize('crisis'); // "crises" (cached)
    
  4. Integration with Laravel Helpers Extend Laravel’s Str helper by wrapping Inflect in a trait:

    use Inflect\Inflect;
    
    trait InflectHelper {
        public static function pluralize($string) {
            return Inflect::pluralize($string);
        }
    }
    

Advanced Patterns

  1. Custom Rules Extend the inflector with domain-specific rules (e.g., for acronyms):

    Inflect::pluralize('NASA'); // "NASAs" (default)
    Inflect::addRule('NASA', 'NASAs', 'NASAs'); // Custom rule
    
  2. Localization Override inflections per language (e.g., Spanish plurals):

    Inflect::setLocale('es');
    Inflect::pluralize('hombre'); // "hombres" (Spanish)
    
  3. API Response Normalization Standardize JSON responses by inflecting keys:

    $data = ['items' => collect($posts)->toArray()];
    $data['posts'] = $data['items']; // Rename key dynamically
    unset($data['items']);
    

Gotchas and Tips

Pitfalls

  1. Memoization Overhead

    • Issue: Memoization caches all inflections globally. Overuse in high-traffic apps may bloat memory.
    • Fix: Clear cache for specific keys if needed:
      Inflect::clearMemoization('special_case');
      
  2. Locale Conflicts

    • Issue: Default locale (English) may not match app requirements (e.g., Spanish/German).
    • Fix: Set locale early in bootstrap:
      // config/app.php (bootstrapServices)
      Inflect::setLocale(config('app.locale'));
      
  3. Edge Cases in Rules

    • Issue: Custom rules may conflict with built-ins (e.g., addRule('foo', 'bar') overriding Inflect::pluralize('foo')).
    • Fix: Test rules in isolation and use descriptive keys.
  4. Thread Safety

    • Issue: Memoization is static; concurrent requests may cause race conditions in edge cases.
    • Fix: Avoid shared state in multi-process environments (e.g., queues).

Debugging Tips

  1. Inspect Rules Dump all registered rules to debug unexpected behavior:

    print_r(Inflect::getRules());
    
  2. Disable Memoization Temporarily disable caching to test rule accuracy:

    Inflect::disableMemoization();
    Inflect::pluralize('edge_case'); // Uncached result
    
  3. Fallback to Defaults Reset to default rules if customizations break:

    Inflect::reset();
    

Extension Points

  1. Add Custom Inflections Extend the package by adding methods to the Inflect class:

    // In a service provider
    Inflect::addMethod('acronymize', function($string) {
        return preg_replace('/([a-z])([A-Z])/', '$1_$2', $string);
    });
    
  2. Override Core Methods Replace entire methods (e.g., for locale-specific logic):

    Inflect::overrideMethod('pluralize', function($word) {
        // Custom logic
        return $word . 's';
    });
    
  3. Integrate with Laravel Events Trigger inflection events (e.g., Inflecting) for observability:

    event(new Inflecting('pluralize', ['word' => 'child']));
    
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.
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle