3 Methods to Get Route Name in Laravel 9

3 Methods to Get Route Name in Laravel 9

In Laravel application, route can be defined with name. It is a unique identifier which can be used for generating URLs or redirecting to specific routes.

This tutorial provides 3 methods how to get route name in Laravel 9 application.

Let's say we have defined the following route named test_index:

routes/web.php

<?php

use App\Http\Controllers\TestController;
use Illuminate\Support\Facades\Route;

Route::get('/', [TestController::class, 'index'])->name('test_index');

Method 1 - 'Route' facade

Laravel provides the Route facade which allows retrieving route name using currentRouteName method.

app/Http/Controllers/TestController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Response;
use Illuminate\Support\Facades\Route;

class TestController extends Controller
{
    public function index(): Response
    {
        return new Response(Route::currentRouteName()); // Output: test_index
    }
}

Method 2 - 'Request' object

Request object allows getting the current route. Its name can be retrieved by using getName method.

app/Http/Controllers/TestController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Http\Response;

class TestController extends Controller
{
    public function index(Request $request): Response
    {
        return new Response($request->route()?->getName()); // Output: test_index
    }
}

Method 3 - 'Request' facade

We can get the current route using Request facade. The getName method allows getting the route name.

app/Http/Controllers/TestController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Response;
use Illuminate\Support\Facades\Request;

class TestController extends Controller
{
    public function index(): Response
    {
        return new Response(Request::route()?->getName()); // Output: test_index
    }
}

Leave a Comment

Cancel reply

Your email address will not be published.