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

String Laravel Package

alhames/string

A lightweight Laravel/PHP helper package providing convenient string utilities and shortcuts for common text operations such as formatting, cleaning, converting case, and working with substrings, making repetitive string handling tasks easier across your application.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require alhames/string
    

    No configuration required—just autoload the facade or helper functions.

  2. First Use Case Convert a string to kebab-case in a Blade template:

    use Alhames\String\Facades\StringHelper;
    
    {{ StringHelper::kebab('HelloWorldExample') }} // Output: "hello-world-example"
    

    Or via helper:

    kebab('HelloWorldExample'); // Same output
    
  3. Where to Look First


Implementation Patterns

Common Workflows

  1. String Sanitization

    // Remove special chars from a slug
    $cleanSlug = StringHelper::slug('Café au Lait!', '-');
    // Output: "cafe-au-lait"
    
  2. Case Conversion

    // Convert API responses to readable format
    $title = StringHelper::title('this_is_a_test');
    // Output: "This Is A Test"
    
  3. Text Wrapping

    // Truncate long text in notifications
    $shortened = StringHelper::limit('Lorem ipsum...', 20);
    // Output: "Lorem ipsum..."
    
  4. Validation Helpers

    // Check if a string is alphanumeric in a Form Request
    if (StringHelper::isAlphaNumeric($input)) { ... }
    

Integration Tips

  • Service Providers: Register the facade in AppServiceProvider if extending:
    public function boot()
    {
        $this->app->singleton(StringHelper::class, function ($app) {
            return new StringHelper();
        });
    }
    
  • Blade Directives: Create custom directives for reusable transformations:
    Blade::directive('kebab', function ($expression) {
        return "<?php echo kebab({$expression}); ?>";
    });
    
    Usage:
    @kebab($variable)
    
  • Model Observers: Auto-sanitize fields on save:
    public function saving(Model $model)
    {
        $model->slug = StringHelper::slug($model->title);
    }
    

Gotchas and Tips

Pitfalls

  1. Locale Sensitivity

    • slug() and title() may not handle non-Latin characters perfectly (e.g., Cafécafe vs. café). Test with your app’s supported locales.
    • Fix: Extend the package or pre-process strings with iconv:
      $normalized = iconv('UTF-8', 'ASCII//TRANSLIT', $string);
      
  2. Helper vs. Facade Conflicts

    • If using both, ensure no naming collisions (e.g., str() helper vs. StringHelper::str()). Prefix facades in code:
      use Facades\StringHelper as StrHelper;
      
  3. Performance in Loops

    • Avoid calling StringHelper methods in tight loops (e.g., processing 10K records). Cache results or batch operations:
      $strings = collect($records)->map(fn ($r) => StringHelper::slug($r->name))->toArray();
      

Debugging

  • Unexpected Output: Use dd() to inspect intermediate strings:
    dd(StringHelper::snake('Hello-World')); // Debug before final use
    
  • Character Encoding Issues: Force UTF-8 encoding if working with legacy data:
    $fixed = mb_convert_encoding($string, 'UTF-8', 'auto');
    

Extension Points

  1. Custom Methods Add a trait to extend functionality:

    use Alhames\String\StringHelper;
    
    class CustomStringHelper extends StringHelper {
        public static function customMethod($str) {
            return strtoupper($str) . '_SUFFIX';
        }
    }
    

    Register the new class in AppServiceProvider.

  2. Override Helpers Publish and modify the helper file:

    composer dump-autoload
    

    Then edit vendor/alhames/string/src/helpers.php.

  3. Configuration No built-in config, but you can create a config file (e.g., config/string.php) to store defaults like:

    return [
        'slug_separator' => '-',
        'default_locale' => 'en_US',
    ];
    

    Then bind it to the helper:

    StringHelper::setConfig(config('string'));
    

Pro Tips

  • Combine with Laravel Collectives: Use StringHelper with Str::of() for chained operations:
    Str::of($string)->kebab()->prepend('prefix_')->__toString();
    
  • API Responses: Standardize responses with StringHelper::snake() for consistency:
    return response()->json(StringHelper::snake($model->toArray()));
    
  • Testing: Mock the facade in PHPUnit:
    $this->mock(StringHelper::class)->shouldReceive('slug')->andReturn('test-slug');
    
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.
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
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