How to use Str Support Library For String Manipulation Methods in Laravel 9?

In thins tutorial we will understand how to use Str support library for string manipulation methods in Laravel 9 with examples. Laravel Str support library helps us with unique ideas to manipulate strings. See such manipulation examples below with the code.

words() method will limit the number of words in a given string. 

$converted = Str::words($str, 10);

length() method will return number of characters in a given string.

$converted = Str::length($str);

title() method will convert string as title. Every word will start with capital letter.

$converted = Str::title($str);

slug() method will give same output as kebab() method.

$converted = Str::slug( $str );

upper() method will convert whole string to capital letters. 

$converted = Str::upper( $str );

ucfirst() method will convert first letter of the string to capital letter. 

$converted = Str::ucfirst( $str );

singular() is a very interesting method. It takes a plural word and returns its singular form. For example, 

input: stories

output: story

$singular = Str::singular($str);

similarly, plural() method will be inverse of singular() method. It will return plural of any English word. 

$plural = Str::plural($str);

random() is also a very interesting method. It will return random string with given number of characters as parameter. 

$random = Str::random(20);

endWith() takes 2 parameters. One string and other ending character to check. It checks whether String is ending with given character or not. The code written bellow will return true. 

$isEndWith = Str::endsWith('story', 'y');

on the other hand, startsWith() takes 2 parameters and check whether string is starting with given letter in second parameter. The code written bellow will return true. 

$isStartWith = Str::startsWith('story', 's');

after() method returns what is left of the string after given character in second parameter. The code below will return ‘ry’ string. 

$afterString = Str::after('story', 'o');

on the other hand, before() will return string before given character in second parameter. The code below will return ‘st’ string. 

$beforeString = Str::before('story', 'o');


For all the laravel manipulation methods, please check Laravel 9.0 docs. If you face any problem leave a comment in comments section. We will address that.