Currently I can get a route in a controller by injecting it into the method I want to use it in.
<?php namespace App\Http\Controllers;
use Illuminate\Routing\Route;
class HomeController extends Controller
{
public function getIndex(Route $route)
{
echo $route->getActionName();
}
}
However I'm trying to perform something similar in middleware but can't get it going.
<?php namespace App\Http\Middleware;
use Closure;
use Illuminate\Routing\Route;
use Illuminate\Contracts\Routing\Middleware;
class SetView implements Middleware {
protected $route;
public function __construct(Route $route)
{
$this->route = $route;
}
public function handle($request, Closure $next)
{
echo $this->route->getActionName();
return $next($request);
}
}
Getting an error.
Unresolvable dependency resolving [Parameter #0 [ <required> $methods ]] in class Illuminate\Routing\Route
Not really sure what to do with that. Don't really care if it's a route or not, but need to get that action name somehow.
If you would like to assign middleware to specific routes, you should first assign the middleware a key in your application's app/Http/Kernel.php file. By default, the $routeMiddleware property of this class contains entries for the middleware included with Laravel.
in global middleware, you can not get route from request directly, but you can get if in a routeMiddleware. so, just use routeMiddleware , and in middleware, $request->route() .
Remove your constructor/put it to default like;
public function __construct(){}
Try accessing the route via the handle method like so;
$request->route();
So you should be able to access the action name like so;
$request->route()->getActionName();
If the route return is null be sure you have registered the middleware within the App/Http/Kernel.php, like so;
protected $middleware = [
...
'Path\To\Middleware',
];
The above is for global middleware
For route specific filtering place the 'Path\To\Middleware',
within the middleware array within RouteServiceProvider.php within the App\Providers
folder.
You can also access the route object via app()->router->getCurrentRoute()
.
Edit:
You could possibly try the following;
$route = Route::getRoutes()->match($request);
$route->getActionName();
This get the route from the RouteCollection
. Be sure to encapsulate this within a try catch as this will throw a NotFoundHttpException
.
For Laravel 5.1.x
In your global middleware
use Illuminate\Support\Facades\Route;
$route = Route::getRoutes()->match($request);
$currentroute = $route->getName();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With