Laravel 9 to_route() and str() New Helper Function Tutorial

Reading Time: 3 minutes
1,082 Views

Inside this article we will see the concept i.e Laravel 9 to_route() and str() New Helper Function Tutorial. Article contains the classified information about new functions of laravel 9 to_route() and str().

Laravel 9 now came with new str() helper function globally that you can use to do string operations fluently just like how you would do with Str::of. In addition to the str() helper, Laravel 9 also came with a convenient to_route() helper function that you can use instead of redirect()->route() for named routes for instance.

Learn More –

Let’s get started.

Laravel Installation

Open terminal and run this command to create a laravel project.

composer create-project laravel/laravel myblog

It will create a project folder with name myblog inside your local system.

To start the development server of laravel –

php artisan serve

URL: http://127.0.0.1:8000

Assuming laravel already installed inside your system.

Example #1: Use of str() Helper

The str function returns a new Illuminate\Support\Stringable instance of the given string. This function is equivalent to the Str::of method.

In old process, we need to import Str class before working with string.

use Illuminate\Support\Str;

Old Process

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Str;

class HomeController extends Controller
{
    public function index()
    {
        $string = "Welcome to Online Web Tutor";

        echo Str::snake($string); // welcome_to_online_web_tutor
    }
}

Replaced with New

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class HomeController extends Controller
{
    public function index()
    {
        $string = "Welcome to Online Web Tutor";

        echo str()->snake($string); // welcome_to_online_web_tutor
    }
}

Available Methods of ‘Str’

upper()

$string = "Online Web Tutor";

echo Str::upper($string); 
// Output: ONLINE WEB TUTOR

echo str()->upper($string); 
// Output: ONLINE WEB TUTOR

replaceLast()

$string = "my_sample_file.php";

echo Str::of($string)->replaceLast('php', 'html')->camel(); 
// Output: mySampleFile.html

echo str($string)->replaceLast('php', 'html')->camel(); 
// Output: mySampleFile.html

Example #2: Use of to_route() Helper

The to_route function generates a redirect HTTP response for a given named route.

Old Process

Route::get('redirectHome', function() {

    return redirect()->route('home');
});

Replace with New

Route::get('redirectHome', function() {
    
    return to_route('home');
});

You can use these helper functions with Laravel v9.

We hope this article helped you to learn Laravel 9 to_route() and str() New Helper Function Tutorial in a very detailed way.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.