Laravel:自定义中间件正在应用于每条路线

时间:2015-11-01 11:46:17

标签: laravel-5.1 laravel-middleware

我创建了一个中间件:

use Closure;
use Gate;
class ACLMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if (Gate::denies('access-post')) {
            abort(403,'Not allowed!!!');
        }
        return $next($request);
    }
}

然后在路线中定义为:

Route::get('/', 'HomeController@index');

Route::group(['middleware' => 'auth','acl'], function () {

    Route::resource('post', 'PostController');
   ...

当我运行它时......它适用于所有路线,即使在/上也是如此。为什么这样?

Kernel.php

<?php

namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{
    /**
     * The application's global HTTP middleware stack.
     *
     * @var array
     */
    protected $middleware = [
        \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
        \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \App\Http\Middleware\VerifyCsrfToken::class,
        \App\Http\Middleware\ACLMiddleware::class,
    ];

    /**
     * The application's route middleware.
     *
     * @var array
     */
    protected $routeMiddleware = [
        'auth'       => \App\Http\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'guest'      => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'acl'        => \App\Http\Middleware\ACLMiddleware::class,
    ];
}

2 个答案:

答案 0 :(得分:2)

您的中间件已在App\Http\Kernel.php注册。

数组:

protected $middleware = ['...'];

定义应该在每个http请求上运行的中间件。在您的情况下,如果您不希望它在每个请求上运行,则需要删除\App\Http\Middleware\ACLMiddleware::class

数组:

protected $routeMiddleware = ['...']; 

定义仅在您指定的位置应用的中间件。这是您的定义所属的地方。

答案 1 :(得分:0)

您需要使用MW类名称将中间件链接到您的路线,例如:Route::post('route', 'Controller@index')->middleware(Authorize::class);