Daljeet Singh
Daljeet Singh

Reputation: 714

How to get name of requested controller and action in middleware Laravel

I am new to Laravel, and i want to get name of requested controller and action in beforefilter middelware.

Thanks, DJ

Upvotes: 21

Views: 22251

Answers (3)

waterloomatt
waterloomatt

Reputation: 3742

Laravel 9

https://laravel.com/docs/9.x/routing#accessing-the-current-route

Accessing The Current Route You may use the current, currentRouteName, and currentRouteAction methods on the Route facade to access information about the route handling the incoming request:

use Illuminate\Support\Facades\Route;
 
$route = Route::current(); // Illuminate\Routing\Route
$name = Route::currentRouteName(); // string
$action = Route::currentRouteAction(); // string

Upvotes: 1

Laravelista77
Laravelista77

Reputation: 71

You can add this (Laravel v7 and above )

use Illuminate\Support\Facades\Route;
....
Route::getCurrentRoute()->getActionMethod() 

Upvotes: 7

Limon Monte
Limon Monte

Reputation: 54389

Laravel 5.6:

class_basename(Route::current()->controller);

Laravel 5.5 and lower:

You can retrieve the current action name with Route::currentRouteAction(). Unfortunately, this method will return a fully namespaced class name. So you will get something like:

App\Http\Controllers\FooBarController@method

Then just separate method name and controller name:

$currentAction = \Route::currentRouteAction();
list($controller, $method) = explode('@', $currentAction);
// $controller now is "App\Http\Controllers\FooBarController"

$controller = preg_replace('/.*\\\/', '', $controller);
// $controller now is "FooBarController"

Upvotes: 35

Related Questions