How to Use Fluent String Operations in Laravel 7

Arie Visser • March 11, 2020

laravel php

Laravel 7 has an excellent new feature, called fluent string operations.

It provides an "object-oriented interface for working with string values", e.g.

ucfirst('hello') . ' my friend.';

// 'Hello my friend.'


use Illuminate\Support\Str;

    ->append(' my friend.'); 

// 'Hello my friend.'

In this post I would like to describe some common string conversions that can be applied by using fluent string operations.

Basic operations

Replace all occurrences of a string

use Illuminate\Support\Str;

Str::of('This is what separates good tea from other tea.')
    ->replace('tea', 'coffee');

// 'This is what separates good coffee from other coffee.'

Check if a string starts with another string

use Illuminate\Support\Str;

Str::of('Where does it begin?')

// false

Extract filename and extension

use Illuminate\Support\Str;

$file = 'my_new.image-file.png';

$filename = Str::of($file)

// 'my_new.image-file'

$extension = Str::of($file)

// 'png'

Abbreviate a name

    ->limit(1, '.');

// J.

The second argument determines the string that will be appended to the end.

Chaining operations

Change the extension of a file

use Illuminate\Support\Str;


// 'my_new.image-file.jpg'

Change a filename to kebab case and add extension

use Illuminate\Support\Str;


// app-new-file.css

Currently undocumented operations

There are some additional operations that cannot be found in the Laravel Documentation.

Get the value between two other strings

use Illuminate\Support\Str;

Str::of('They drink coffee')
    ->between('They ', ' coffee');

// drink

Convert Class@method to class and method

use Illuminate\Support\Str;


// ['UserController', 'show']

Pluralize a studly case string

use Illuminate\Support\Str;


// MyApplications

Generate a random string

use Illuminate\Support\Str;


// Random string of 16 characters

Convert string to title case

use Illuminate\Support\Str;

Str::of('what is this article about?')->title();

// What Is This Article About?

There are also some methods available concerning uuids, which you can find in \Illuminate\Support\Str.php

I hope you enjoyed this post. You can find some unit tests for these examples in this repository.