How to Get Current Route Name in Laravel?

Laravel 9 , Laravel

Nicesnippets

27-07-2022


How to Get Current Route Name in Laravel?

hi dev,

This tutorial shows you laravel get current route name. let’s discuss about laravel get current route name in view. This article goes in detailed on how to get current route name in laravel. This post will give you simple example of how to get current route name in middleware laravel.

You can use this example with laravel 6, laravel 7, laravel 8 and laravel 9 version.

Here, Creating a basic example of get current route name in laravel.

Laravel Get Route Name in Controller File :


Example 1 :

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class PostController extends Controller

{

public function index(Request $request)

{

$routeName = $request->route()->getName();

dd($routeName);

}

}

Output :

"post.index"

Example 2 :

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use Illuminate\Support\Facades\Route;

class PostController extends Controller

{

public function index(Request $request)

{

$routeName = Route::currentRouteName();

dd($routeName);

}

}

Output :

"post.index"

Laravel Get Route in Blade File :

Example 1 :

<p>{{ Route::currentRouteName() }}</p>

Output :

post.index

Example 2 :

<p>{{ Route::getCurrentRoute()->getActionName(); }}</p>

Output :

App\Http\Controllers\PostController@index

Laravel Get Route in Middleware File :

Example 1 :

<?php

namespace App\Http\Middleware;

use Closure;

use Illuminate\Http\Request;

class CheckAge

{

/**

* Handle an incoming request.

*

* @param \Illuminate\Http\Request $request

* @param \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse) $next

* @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse

*/

public function handle(Request $request, Closure $next)

{

$routeName = $request->route()->getName();

dd($routeName);

return $next($request);

}

}

Output :

"post.index"

I hope it can help you...