str()

str() creates a fluent, chainable string object.

Syntaxstr('Hello world')->slug();

The str() helper returns a fluent Stringable instance, letting you chain string operations in a readable pipeline. Call toString() (or echo it) to get the final result.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • A controller action uses the str() helper to start a fluent chain that trims, slugifies, and limits a user-submitted title without importing the Str class.
  • A Blade component calls str($product->description)->words(30)->value() inline to truncate product descriptions for card previews.
  • A test uses str() to build expected strings dynamically and compare them with assertions, keeping the test concise.

More examples

Fluent string via str() helper

The str() global helper returns a fluent Stringable object, so you can chain transformations and extract the result with value().

Example · php
$slug = str('  My New Blog Post! ')
    ->trim()
    ->slug()
    ->value();
// => 'my-new-blog-post'

Chain multiple transformations

Demonstrates two independent fluent pipelines: one for formatting a snake_case label and one for creating a plain-text article preview.

Example · php
$label = str('user_profile_settings')
    ->replace('_', ' ')
    ->title()
    ->value();
// => 'User Profile Settings'

$preview = str($article->body)
    ->stripTags()
    ->words(25)
    ->value();
// First 25 words of the body, HTML stripped

Conditionally modify a string

Stringable's when() method applies a transformation only if the first argument is truthy, enabling conditional pipeline steps.

Example · php
$name = str('alice')
    ->when(true,  fn($s) => $s->ucfirst())
    ->when(false, fn($s) => $s->upper())
    ->value();
// => 'Alice'
// The second when() is skipped because condition is false

Discussion

  • Be the first to comment on this lesson.