Laravel-路由组和中间件
标签(空格分隔): php
定义路由组 Route::group([\'prefix\'=>\'Anime\'], function(){ Rout::match([\'get\', \'post\'], \'login\', \'Admin\LoginController@login) Route::group([\'middleware\'=>\'CheckToken\', function(){ Rout::match([\'get\', \'post\'], \'index\',\'Admin\LoginController@index) }) }); prefix : 路由前缀 对应生成的路由是 /Anime/login match: http请求方式 get | post | delete middleware : 中间件 中间件 1 要创建一个新的中间件,可以通过 Artisan 命令 make:middleware: php artisan make:middleware CheckToken 2 生成文件的位置在 app\Http\Middleware\CheckToken.php 在 handle 方法里完成你的中间件 如:登录验证, 记录日志 handle分为 :中间件之前/之后 3 注册中间件 app\Http\Kernel.php 注册在 routeMiddleware 数组中: <?php namespace App\Http; use Illuminate\Foundation\Http\Kernel as HttpKernel; class Kernel extends HttpKernel { /** * The application\'s global HTTP middleware stack. * * These middleware are run during every request to your application. * * @var array */ ### 全局的中间件 protected $middleware = [ \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class, \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class, \App\Http\Middleware\TrimStrings::class, \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class, ]; /** * The application\'s route middleware groups. * * @var array */ ## 中间件组 \routes\ web => web.php api=> api.php 文件中所有的路由都必须通过中间件的处理 protected $middlewareGroups = [ \'web\' => [ \App\Http\Middleware\EncryptCookies::class, \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class, \Illuminate\Session\Middleware\StartSession::class, // \Illuminate\Session\Middleware\AuthenticateSession::class, \Illuminate\View\Middleware\ShareErrorsFromSession::class, \App\Http\Middleware\VerifyCsrfToken::class, \Illuminate\Routing\Middleware\SubstituteBindings::class, \App\Http\Middleware\CheckToken::class ], \'api\' => [ \'throttle:60,1\', \'bindings\', ], ]; /** * The application\'s route middleware. * * These middleware may be assigned to groups or used individually. * * @var array */ # 路由组中间件 protected $routeMiddleware = [ \'auth\' => \Illuminate\Auth\Middleware\Authenticate::class, \'auth.basic\' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class, \'bindings\' => \Illuminate\Routing\Middleware\SubstituteBindings::class, \'can\' => \Illuminate\Auth\Middleware\Authorize::class, \'guest\' => \App\Http\Middleware\RedirectIfAuthenticated::class, \'throttle\' => \Illuminate\Routing\Middleware\ThrottleRequests::class, \'CheckToken\' => \App\Http\Middleware\CheckToken::class, ]; }