Str Introduction

The Str class provides dozens of static methods for working with strings.

Syntax\Illuminate\Support\Str::method($string);

Illuminate\Support\Str is a facade full of static string helpers. They cover casing, slugs, truncation, searching and much more.

You can call any of them statically, for example Str::upper('hi'). In runnable examples here we use the fully-qualified name.

Example

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

When to use it

  • A developer replaces a chain of strtolower(), str_replace(), and ucwords() calls with concise Str:: helpers, making the transformation intent immediately clear.
  • A CMS plugin uses Str:: methods to sanitise user-submitted content — converting to slug, limiting length, and masking email addresses — before storing records.
  • A test factory generates realistic placeholder data using Str::random() for tokens and Str::title() for formatted names.

More examples

Import and call a Str method

Shows the basic import and three common Str:: calls: slug generation, camel-case conversion, and upper-casing.

Example · php
use Illuminate\Support\Str;

$slug  = Str::slug('Hello World');       // 'hello-world'
$camel = Str::camel('user_first_name');  // 'userFirstName'
$upper = Str::upper('laravel');          // 'LARAVEL'

Use the fluent string builder

Str::of() returns a fluent Stringable object that lets you chain transformations before extracting the final string with value().

Example · php
$result = Str::of('  Hello, Laravel World!  ')
    ->trim()
    ->title()
    ->replace('Laravel', 'PHP')
    ->value();
// => 'Hello, PHP World!'

Mix Str methods for content sanitisation

Chains PHP's trim/strip_tags with Str::title, Str::slug, and Str::limit to safely normalise a user-supplied post title.

Example · php
$raw   = '  Unsafe <script> Post Title!! ';
$clean = Str::title(strip_tags(trim($raw)));  // 'Unsafe  Post Title!!'
$slug  = Str::slug($clean);                    // 'unsafe-post-title'
$short = Str::limit($slug, 30);               // safe for DB column

Discussion

  • Be the first to comment on this lesson.