1.创建中间件
在app/Http/Middleware 下创建同一个php文件文件内容
<?php
namespace App\Http\Middleware;
use Illuminate\Http\Response;
use Closure;
class CheckToken
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
return $next($request);
}
}
可通过Artisan 快速创建
php artisan make:middleware CheckToken
2.注册中间件
支持全局中间件 ----------在 protected $middleware 下配置
protected $middleware = [
\App\Http\Middleware\TrustProxies::class,
\Fruitcake\Cors\HandleCors::class,
\App\Http\Middleware\CheckForMaintenanceMode::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\App\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
\App\Http\Middleware\CheckToken::class, 新注册的全局中间件
];
分配中间件到指定路由 在protected $routeMiddleware 下配置
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
'CheckToken' => \App\Http\Middleware\CheckToken::class, //新注册中间件
];
分配中间件
-------------------单个路由分配单个中间件-----------------
Route::get('/', function () {
//
})->middleware('token');
-----------------单个路由分配多个中间件-------------
Route::get('/', function () {
//
})->middleware('token', 'auth');
---------------给一组路由分配多个中间件----------------------
Route::middleware(['first', 'second'])->group(function () {
Route::get('/', function () {
// Uses first & second Middleware
});
Route::get('user/profile', function () {
// Uses first & second Middleware
});
});