Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

The new str() and to_route() helpers in Laravel 9

February 12, 2022 ·

Before Laravel 9, when you wanted to interact with strings you would either use the Illuminate\Support\Str class like so.

use Illuminate\Support\Str;
 
$result = Str::endsWith('PHP is awesome', 'PHP');

// Outputs: true

Or if you want to do these string operations fluently, you can use the Illuminate\Support\Str::of that returns the instance of Illuminate\Support\Stringable class like so.

use Illuminate\Support\Str;

$input = 'this is test file.php';

$output = Str::of($input)
                ->replaceLast('php', 'html')
                ->camel();

// thisIsTestFile.html

But with the release of Laravel 9, there’s one more way to do the same.

The str() helper

Laravel 9 now comes with a new str() helper function globally that you can use to do string operations fluently just like how you would do with Str::of.

So, the previous example can be rewritten using str() like so.

$input = 'this is test file.php';

$output = str($input)
                ->replaceLast('php', 'html')
                ->camel();

// thisIsTestFile.html

As you can tell, the one advantage this helper method brings is now you don’t have to import the Illuminate\Support\Str class altogether. So, that’s one less overhead. It just works!

And on top of this, it’s more elegant and compact.

Additionally, if you don’t provide any argument to the str() function, the function still returns an instance of Illuminate\Support\Str that you can use to do the fluent operations further.

$output = str()->camel('test file.php');

// testFile.php

The to_route() helper

In addition to the str() helper, Laravel 9 also comes with a convenient to_route() helper function that you can use instead of redirect()->route() for named routes for instance.

So, if we have a named route called home, here’s what it looks like in both, Pre and Post Laravel 9.

// Pre Laravel 9
Route::get('redirectHome', function() {
    return redirect()->route('home');
});

// Post Laravel 9
Route::get('redirectHome', function() {
    return to_route('home');
});

As you can tell, the to_route() helper function works the same way as redirect()->route() but it’s a little more expressive and concise than the latter.

Learn the fundamentals of PHP 8 (and 8.1), the latest version of PHP, and how to use it today with my new book PHP 8 in a Nutshell. It's a no-fluff and easy-to-read guide to the latest features and nitty-gritty details of PHP 8. So, if you're looking for a quick and easy way to PHP 8, this is the book for you.

👋 Hi there! I'm Amit. I write articles about all things web development. If you like what I write and want me to continue doing the same, I would like you buy me some coffees. I'd highly appreciate that. Cheers!

Comments?