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

Str Laravel Package

php-standard-library/str

Lightweight string utility library for PHP, providing common helpers for formatting, parsing, and safe string handling. Designed as a simple “standard library” add-on with a small API surface and easy composer integration.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require php-standard-library/str
    

    No additional configuration is required—Laravel’s autoloader will handle the package automatically.

  2. First Use Case: Replace repetitive or error-prone string operations in Laravel controllers, services, or Blade templates. For example:

    use PhpStandardLibrary\Str;
    
    // Replace native PHP functions
    $trimmed = Str::trim('  hello  '); // 'hello'
    $slug = Str::slug('Hello World');   // 'hello-world'
    
    // Use fluent interface for complex operations
    $formatted = Str::of('  USER_NAME  ')
        ->trim()
        ->lower()
        ->replace('_', ' ')
        ->title()
        ->value(); // 'User Name'
    
  3. Where to Look First:

    • Core Methods: Focus on Str::of() for fluent operations and static methods like Str::trim(), Str::slug(), Str::title(), and Str::ascii().
    • Laravel Integration: Use the package in:
      • Controllers: Sanitize or format user input.
      • Services: Standardize string outputs (e.g., slugs for URLs).
      • Blade Templates: Format dynamic text (e.g., {{ Str::title($post->title) }}).
    • Documentation: The package’s GitHub README and inline PHPDoc comments are sufficient for quick reference.

Implementation Patterns

Common Workflows in Laravel

1. Request Validation and Sanitization

Replace manual string cleaning in Laravel’s FormRequest classes:

use PhpStandardLibrary\Str;

public function rules()
{
    return [
        'username' => 'required|string|max:255',
        'bio' => 'nullable|string',
    ];
}

public function prepareForValidation()
{
    $this->merge([
        'username' => Str::of($this->username)->trim()->lower()->value(),
        'bio' => Str::of($this->bio)->trim()->value(),
    ]);
}

2. Model Attribute Formatting

Use accessors/mutators to standardize string outputs:

use PhpStandardLibrary\Str;

class Post extends Model
{
    public function getSlugAttribute()
    {
        return Str::slug($this->title);
    }

    public function setTitleAttribute($value)
    {
        $this->attributes['title'] = Str::of($value)->trim()->title()->value();
    }
}

3. API Response Formatting

Standardize JSON payloads in controllers:

use PhpStandardLibrary\Str;

public function show(Post $post)
{
    return response()->json([
        'id' => $post->id,
        'title' => Str::title($post->title),
        'slug' => Str::slug($post->title),
        'excerpt' => Str::of($post->body)->limit(200)->append('...')->value(),
    ]);
}

4. Blade Template Helpers

Register a Blade directive for reusable string operations:

// In AppServiceProvider@boot()
Blade::directive('format', function ($expression) {
    return "<?php echo PhpStandardLibrary\Str::of({$expression})->trim()->title()->value(); ?>";
});

Usage in Blade:

<h1>@format($post->title)</h1>

5. Testing String Logic

Simplify assertions in PHPUnit/Pest tests:

use PhpStandardLibrary\Str;

it('formats the title correctly', function () {
    $title = Str::of('  hello world  ')->title()->value();
    expect($title)->toBe('Hello World');
});

6. Composable Pipelines

Chain methods for complex transformations:

$cleaned = Str::of($rawInput)
    ->trim()
    ->lower()
    ->replace(['&', ' ', '.'], '-')
    ->slug()
    ->prepend('doc-')
    ->value();

7. Replacing Laravel’s Str Facade

If you prefer this package over Laravel’s Str helper, alias it globally:

// In config/app.php
'aliases' => [
    'Str' => PhpStandardLibrary\Str::class,
];

Now use Str::slug() instead of Str::of($input)->slug().


Integration Tips

1. Leverage Laravel’s Service Container

Bind the package to a custom interface for dependency injection:

$this->app->bind(
    StringFormatter::class,
    fn () => new PhpStandardLibrary\Str()
);

Usage:

public function __construct(private StringFormatter $formatter) {}

public function formatTitle(string $input): string
{
    return $this->formatter->of($input)->title()->value();
}

2. Customize Default Behavior

Extend the package by creating a wrapper class:

class AppStr extends PhpStandardLibrary\Str
{
    public static function customSlug(string $input, string $separator = '-')
    {
        return parent::of($input)
            ->trim()
            ->lower()
            ->replace([' ', '_'], $separator)
            ->value();
    }
}

3. Use in Artisan Commands

Format CLI outputs consistently:

use PhpStandardLibrary\Str;

class GenerateSlugCommand extends Command
{
    protected function handle()
    {
        $slug = Str::slug($this->argument('title'));
        $this->info("Generated slug: {$slug}");
    }
}

4. Static Analysis and IDE Support

  • Add @mixin annotations in PHPStorm for better autocompletion:
    /**
     * @mixin \PhpStandardLibrary\Str
     */
    class Str {}
    
  • Use PHPStan to enforce consistent string handling:
    parameters:
        string_formatter: PhpStandardLibrary\Str::class
    

5. Performance Considerations

  • For bulk operations (e.g., processing 1000+ strings), benchmark against native PHP functions:
    // Benchmark Str::slug() vs. mb_strtolower() + str_replace()
    
  • Cache results if transformations are expensive and repeated (e.g., in a loop).

Gotchas and Tips

Pitfalls

1. Unicode Handling Quirks

  • While the package is Unicode-aware, edge cases may exist (e.g., combining characters, surrogate pairs). Test with:
    $text = "Café\u0301"; // "Café" with combining acute accent
    $slug = Str::slug($text); // Ensure it handles diacritics correctly
    
  • Fix: Use Str::ascii() to normalize Unicode strings if needed.

2. Null or Non-String Inputs

  • The package may throw exceptions or return unexpected results for null or non-string inputs. Handle explicitly:
    $safeSlug = Str::of($maybeNullInput ?? '')
        ->slug()
        ->value();
    
  • Tip: Add a wrapper method to your app’s Str class:
    public static function safeSlug(?string $input): string
    {
        return Str::of($input ?? '')->slug()->value();
    }
    

3. Method Chaining Pitfalls

  • Fluent methods return the Str object, but some (like value()) return the result. Chain carefully:
    // Wrong: Returns the Str object, not the string
    $result = Str::of('test')->value()->upper();
    
    // Correct:
    $result = Str::of('test')->upper()->value();
    
  • Tip: Use tap() for debugging intermediate steps:
    Str::of($input)
        ->tap(fn ($str) => logger()->debug($str->value()))
        ->slug();
    

4. Locale-Specific Transformations

  • Methods like Str::title() may not handle locale-specific rules (e.g., Turkish dotted 'i'). Test with:
    $turkish = "merhaba dünya"; // Turkish "hello world"
    $title = Str::title($turkish); // Ensure 'i' is not capitalized as 'İ'
    
  • Fix: Use Str::ascii() or implement custom logic.

5. Laravel Facade Conflicts

  • If you alias Str to this package, ensure no conflicts with Laravel’s Str facade:
    composer show laravel/framework | grep -i str
    
  • **Tip
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