Laravel中创建中间件
要在 laravel 里新建一个中间件,首先 SSH 到服务器上,在 Laravel 目录下执行:
php artisan make:middleware test
其中 test
是你中间件的名字。
然后,在 app/Http/Kernel.php
中注册它,首先打开该文件,
然后拉到最下面,有一行 protected $routeMiddleware
,往里面添加 ↓
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::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,
'test' => \App\Http\Middleware\test::class // <= 添加这行
];
保存。
如果要对某条特定的route使用中间件,就在那条route后面添加 ->middleware('test')
,
比如:
Route::get('/', function () {
return view('index');
})->middleware('test');