1.创建中间件
使用 artisan
命令行工具创建中间件类 CheckLoginMiddleware
php artisan make:middleware CheckLoginMiddleware
2.注册中间件
在
/app/Http/Kernel.php
中注册中间件
- 全局中间件
protected $middleware = [ \App\Http\Middleware\CheckLoginMiddleware::class,];
- 路由中间件
protected $routeMiddleware = [ 'checkLogin' => \App\Http\Middleware\CheckLoginMiddleware::class,];
3.使用中间件
Route::group(['middleware' => 'checkLogin'], function () { // routes ..});Route::get('/admin/index', 'AdminController@index')->middleware('checkLogin');
4. 中间件参数
- 在中间件中..
public function handle($request, Closure $next, $name, $age){ \$arr = [\$name, \$age]; print_r(\$arr); return \$next(\$request);}
- 在路由中..
Route::get('/test', function () { // Array ( [0] => name [1] => 18 )})->middleware('my_test:alex,18');