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

spatie/string

Fluent string wrapper for PHP. Wrap a value with string() and chain helpers like between(), toUpper()/toLower(), etc. Supports offset access and mutation via array syntax. Great for readable, composable string transformations.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require spatie/string
    

    No configuration is required—just use the facade or helper directly.

  2. First Use Case: Convert a string to snake_case, camelCase, or kebab-case instantly:

    use Spatie\String\String;
    
    $string = String::of('HelloWorld')->snake(); // "hello_world"
    $string = String::of('hello_world')->camel(); // "helloWorld"
    $string = String::of('Hello World')->kebab(); // "hello-world"
    
  3. Facade Alternative: Use the String facade for cleaner syntax:

    use Spatie\String\Facades\String;
    
    String::of('TestString')->studly(); // "TestString"
    

Implementation Patterns

Common Workflows

  1. Model Attribute Formatting: Dynamically format database fields before/after saving:

    protected $casts = [
        'title' => 'string:kebab', // Store as kebab-case
    ];
    
    public function setTitleAttribute($value) {
        $this->attributes['title'] = String::of($value)->kebab();
    }
    
  2. Request Validation & Sanitization: Clean user input before processing:

    $cleaned = String::of(request('user_input'))
        ->trim()
        ->ascii()
        ->lower();
    
  3. URL & Route Generation: Convert strings to URL-friendly formats:

    $slug = String::of('Product Name')->slug(); // "product-name"
    route('products.show', ['slug' => $slug]);
    
  4. Dynamic Query Building: Safely construct query conditions:

    $searchTerm = String::of(request('q'))
        ->trim()
        ->lower();
    
    $results = Model::where('name', 'like', "%{$searchTerm}%")->get();
    

Integration Tips

  • Laravel Service Providers: Bind the String class to the container for dependency injection:

    $this->app->bind('string', function () {
        return new String();
    });
    
  • Blade Directives: Create custom Blade helpers:

    Blade::directive('titleCase', function ($expression) {
        return "<?php echo \\Spatie\\String\\String::of({$expression})->title(); ?>";
    });
    

    Usage:

    <h1>{{ titleCase('hello world') }}</h1> <!-- "Hello World" -->
    
  • API Responses: Standardize response formatting:

    return response()->json([
        'data' => String::of($model->name)->title()
    ]);
    

Gotchas and Tips

Pitfalls

  1. Locale Sensitivity:

    • Methods like title() or slug() may behave unexpectedly with non-Latin characters.
    • Fix: Use locale() to specify language rules:
      String::of('café')->slug('fr'); // "cafe" (French rules)
      
  2. Edge Cases in Trimming:

    • trim() removes all whitespace (including newlines/tabs).
    • Fix: Use trim() + replaceMatches('/\s+/', ' ') for controlled trimming.
  3. Case Conversion Quirks:

    • studly() converts underscores to camelCase but preserves existing camelCase:
      String::of('hello_world')->studly(); // "HelloWorld"
      String::of('helloWorld')->studly();  // "HelloWorld" (unchanged)
      
  4. Slug Collisions:

    • slug() may generate duplicates (e.g., "hello-world" and "hello-world-1").
    • Fix: Append a counter manually or use a package like spatie/laravel-sluggable.

Debugging

  • Inspect Intermediate Steps: Chain methods and log results to debug:

    $steps = [
        String::of('  Hello_World  ')->trim(),
        String::of('Hello_World')->ascii(),
        String::of('Hello_World')->slug(),
    ];
    
  • Check for Hidden Characters: Use String::of($str)->dump() to reveal non-printable characters (e.g., \u200B zero-width spaces).

Extension Points

  1. Custom Rules: Extend the String class to add domain-specific methods:

    class CustomString extends String {
        public function toAcronym(): string {
            return strtoupper(substr($this->value, 0, 3));
        }
    }
    
  2. Override Default Behavior: Replace the slug() method in a service provider:

    String::macro('slug', function () {
        return parent::slug()->replace(['&', '?'], '');
    });
    
  3. Performance:

    • Reuse String instances for repeated operations:
      $string = String::of($input);
      $slug = $string->slug();
      $title = $string->title();
      
    • Avoid recreating the String object in loops.
  4. Testing: Mock the String facade for isolated tests:

    $this->mock(Spatie\String\Facades\String::class)
        ->shouldReceive('of')
        ->andReturn(String::of('Mocked'));
    
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.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport