Laravel 9 New Helper Functions

There are two new helper function in Laravel 9. the first one is str() which cretes a stringable object. It’s an alias to the Str::of($string). Str::of gives you an obejct oriented way to manipulate a string. So for example:

Str::of('Hello World')->upper();

This will make the string ‘Hello World’ upper case. In laravel 9 the equivalent code is:

str('Hello World')->upper();

Let’s look deeper into the str function implementation:

function str($string = null)
    if (func_num_args() === 0) {
        return new class
            public function __call($method, $parameters)
                return Str::$method(...$parameters);

            public function __toString()
                return '';

    return Str::of($string);

If we call the string function and we don’t pass it a string, it sets up an anonymous class and it calls a magic method to forward any method calls.

Another helper function which is a simple way to redirect. If we had a names route to take us to the home page:

Route::get('/', function () {
    return view('welcome');

When we redirect, we can use the to_route() to redirect us to any named route.

return to_route('home');

The to_route() function is the same as the following, which is functionally identical:

return redirect->route('home');

The following is the helper function in laravel:

function to_route($route, $parameters = [], $status = 302, $headers = [])
    return redirect()->route($route, $parameters, $status, $headers);

Leave a Reply

Your email address will not be published.