The new str() and to_route() helpers in Laravel 9
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.
Like this article?
Buy me a coffee👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.