Laravel Magazine
Fluent String Helpers Every Laravel Developer Should Know

Fluent String Helpers Every Laravel Developer Should Know

Eric Van Johnson ·

Raw PHP string manipulation reads inside out. You end up nesting trim() inside strtolower() inside str_replace(), and by the time you parse it you have forgotten what you were doing. Laravel's fluent string helper wraps a string in a Stringable object so you can chain transformations left to right, in the order they actually happen.

Starting a Chain

Kick off a fluent chain with the Str::of() method or the global str() helper:

use Illuminate\Support\Str;

$slug = Str::of('  The PHP Architect Guide!  ')
    ->trim()
    ->lower()
    ->slug();

// "the-php-architect-guide"

Read top to bottom, that is exactly the sequence of operations. Compare it to the nested equivalent and the win is obvious.

Everyday Methods

A handful of methods cover most day-to-day needs:

Str::of('laravel-magazine')->headline();      // "Laravel Magazine"
Str::of('Hello World')->slug();                // "hello-world"
Str::of('foobar')->contains('bar');            // true
Str::of('read-my-post-please')->replace('-', ' '); // "read my post please"
Str::of('a long article body')->limit(10);     // "a long art..."
Str::of('UserProfileController')->snake();      // "user_profile_controller"

headline() is a quiet favorite for turning identifiers into display text. slug() is what you reach for on every URL-friendly title.

Getting a Plain String Back

A Stringable casts to a string automatically when echoed or interpolated, so in Blade you rarely need to think about it. When you need the raw value in PHP, call toString() or cast it:

$value = Str::of('Laravel')->upper()->toString(); // "LARAVEL"

Conditionals in the Chain

Stringable mixes in the same when() behavior you find on queries, so you can branch without leaving the chain:

$name = Str::of($user->name)
    ->when($user->isAdmin(), fn ($string) => $string->append(' (Admin)'));

Pattern Matching Without preg_

Two methods save you from reaching for raw regular expressions in the common cases:

Str::of('order-4815')->match('/[0-9]+/');   // "4815"
Str::of('a1b2c3')->matchAll('/[0-9]/');      // collection of ["1", "2", "3"]
Str::of('draft-post')->isMatch('/^draft/');  // true

Note that matchAll() returns a Laravel collection, so you can pipe straight into map, filter, and the rest.

The fluent string API does not do anything the underlying PHP functions cannot, but it makes the code describe the transformation in the order a reader expects. That readability compounds across a codebase.

Further Reading

Stay Updated

Subscribe to our newsletter

Get latest news, tutorials, community articles and podcast episodes delivered to your inbox.

Weekly articles
We send a new issue of the newsletter every week on Friday.
No spam
We'll never share your email address and you can opt out at any time.