要创建一个新的中间件,则可以使用 make:middleware 这个 Artisan 命令:

此命令将会在 app/Http/Middleware 目录内设定一个名称为 CheckAge 的类。在这个中间件内我们只允许请求的年龄 age 变量大于 200 时才能访问路由,否则,我们会将用户重定向到首页「home」这个 URI 上。

如你所见,若是 age 小于 200,中间件将会返回 HTTP 重定向给用户端,否则,请求将会进一步传递到应用程序。只需调用带有$request的$next方法,即可将请求传递到更深层的应用程序(相当于允许通过中间件)。
HTTP 请求在实际碰触到应用程序之前,最好是可以层层通过中间件。每一层都可以对请求进行检查,甚至完全拒绝请求。
若是希望每个 HTTP 请求都经过一个中间件,只要将中间件的类加入到app/Http/Kernel.php的$middleware属性清单列表中。
如果你要指派中间件给特定路由,你得先在app/Http/Kernel.php给中间件设置一个好记的键,默认情况下,这个文件内的$routeMiddleware属性已包含了 Laravel 目前设置的中间件,你只需要在清单列表中加上一组自定义的键即可。

中间件一旦在 HTTP kernel 文件内被定义,即可在路由选项内使用 middleware 键值指定:

为路由指定多个中间件:

你可以使用完整类名作为路由指派中间件。

中间件组#
有时候你可能想要通过指定一个键名的方式将相关中间件分到一个组里面,从而更方便将其分配到路由中,这可以通过使用 HTTP Kernel 的$middlewareGroups实现。
Laravel 自带了开箱即用的web和api两个中间件组以包含可以应用到 Web UI 和 API 路由的通用中间件:

中间件组可以被分配给路由和控制器动作,使用和单个中间件分配同样的语法。再次申明,中间件组的目的只是让一次分配给路由多个中间件的实现更加简单:

例子:
创建中间件
php artisan make:middleware AdminMiddleware
中间件编写登录验证
public function handle($request, Closure $next) { if( !session()->get('userInfo') ){ return redirect('admin/login'); } return $next($request); }
注册中间件 (Kernel.php)
protected $middlewareGroups = [ 'web' => [ AppHttpMiddlewareEncryptCookies::class, IlluminateCookieMiddlewareAddQueuedCookiesToResponse::class, IlluminateSessionMiddlewareStartSession::class, // IlluminateSessionMiddlewareAuthenticateSession::class, IlluminateViewMiddlewareShareErrorsFromSession::class, AppHttpMiddlewareVerifyCsrfToken::class, IlluminateRoutingMiddlewareSubstituteBindings::class, IlluminateSessionMiddlewareStartSession::class, ], 'api' => [ 'throttle:60,1', 'bindings', ], ];
使用:
<?php namespace AppHttpControllersAdmin; use AppHttpControllersBaseController; use IlluminateHttpRequest; //use DB; use IlluminateSupportFacadesDB; use AppModeladmin; class IndexController extends BaseController { public function __construct(){ $this->middleware('admin.auth')->except(['login','signin']); }
}