Hidden Methods Intermediate Since Laravel 9.x

Fluent Strings: whenContains()

Conditionally transform a string only if it contains a given substring — part of the powerful Stringable fluent API.

Overview

Laravel's Str::of() (or the str() helper) returns a Stringable object with dozens of chainable methods. Among the less-known are the conditional methods like whenContains(), whenStartsWith(), whenEndsWith(), whenIs(), and whenEmpty().

Usage

use Illuminate\Support\Str;

str('[email protected]')
    ->whenContains('@', fn ($str) => $str->before('@'))
    ->upper()
    ->toString();
// 'TAYLOR'

Other conditional methods:

str('Hello World')
    ->whenStartsWith('Hello', fn ($str) => $str->append('!!!'))
    ->toString();
// 'Hello World!!!'

str('')
    ->whenEmpty(fn ($str) => $str->append('default'))
    ->toString();
// 'default'

You can also provide an "else" callback as the third argument:

str('plain-text')
    ->whenContains('@', 
        fn ($str) => $str->before('@'),
        fn ($str) => $str->append('@unknown'),
    )
    ->toString();
// 'plain-text@unknown'

When to Use

  • Parsing or transforming strings conditionally without breaking a fluent chain
  • Processing email addresses, URLs, file paths, or user input
  • Replacing if/else blocks with a more expressive chain