Laravel 的中间件不适用于控制器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31418662/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel's Middleware not working on Controller
提问by omer Farooq
I have a middleware called 'AdminMiddleware', which is being used in the constructor of a class. For some reason the middleware is not called from the constructor, although the constructor function is being run. I tried doing a die dump on the adminMiddleware file but it seems like it just ignores this file.
我有一个名为“AdminMiddleware”的中间件,它正在类的构造函数中使用。出于某种原因,虽然构造函数正在运行,但并未从构造函数调用中间件。我尝试在 adminMiddleware 文件上做一个 die dump,但它似乎只是忽略了这个文件。
namespace App\Http\Controllers\SuperAdmin;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
class dashboard extends Controller
{
protected $user;
public function __construct()
{
$this->middleware('admin');
$this->user = Auth::User();
}
//Kernel.php
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'superadmin' => \App\Http\Middleware\SuperAdminMiddleware::class,
'admin' => \App\Http\Middleware\AdminMiddleware::class,
];
For some project requirements i cant use the middleware directly on the routes. Any help is appreciated, i am using laravel 5.1.
对于某些项目要求,我不能直接在路由上使用中间件。任何帮助表示赞赏,我正在使用 laravel 5.1。
回答by jedrzej.kurylo
You need to do 2 things to enable middleware in the controller:
您需要做两件事才能在控制器中启用中间件:
Register middleware in $routeMiddleware in your App\Http\Kernel.php
protected $routeMiddleware = [ 'admin' => 'App\Http\Middleware\AdminMiddleware', ];
Enable middleware in your controller, using middleware's key, not class name:
$this->middleware('admin');
在您的 App\Http\Kernel.php 中的 $routeMiddleware 中注册中间件
受保护的 $routeMiddleware = [ 'admin' => 'App\Http\Middleware\AdminMiddleware', ];
在控制器中启用中间件,使用中间件的键,而不是类名:
$this->middleware('admin');
回答by Alex Chiang
I have the same problem, and solve it by composer dump-autoload. My problem is change the file name and not regenerate the autoload. I hope it works for you.
我有同样的问题,并通过 composer dump-autoload 解决它。我的问题是更改文件名而不是重新生成自动加载。我希望这个对你有用。
回答by Johnny Fekete
I ran into the same issue, and apparently route caching also caches middlewares.
我遇到了同样的问题,显然路由缓存也缓存了中间件。
So php artisan route:clear
solved it in my case.
所以php artisan route:clear
在我的情况下解决了它。