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.'

becomes

use Illuminate\Support\Str;

Str::of('hello')
    ->ucfirst()
    ->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?')
    ->startsWith('Whiskey');

// false

Extract filename and extension

use Illuminate\Support\Str;

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

$filename = Str::of($file)
    ->beforeLast('.'); 

// 'my_new.image-file'

$extension = Str::of($file)
    ->afterLast('.');

// 'png'

Abbreviate a name

Str::of('John')
    ->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;

Str::of('my_new.image-file.png')
    ->beforeLast('.')
    ->append('.jpg'); 

// 'my_new.image-file.jpg'

Change a filename to kebab case and add extension

use Illuminate\Support\Str;

Str::of('NewFile')
    ->prepend('app')
    ->kebab()
    ->finish('.css');

// 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;

Str::of('UserController@show')->parseCallback();

// ['UserController', 'show']

Pluralize a studly case string

use Illuminate\Support\Str;

Str::of('MyApplication')->pluralStudly();

// MyApplications

Generate a random string

use Illuminate\Support\Str;

Str::random(16);

// 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.