Laravel-路由组和中间件
标签(空格分隔): php
定义路由组
Route::group(['prefix'=>'Anime'], function(){
Rout::match(['get', 'post'], 'login', 'AdminLoginController@login)
Route::group(['middleware'=>'CheckToken', function(){
Rout::match(['get', 'post'], 'index','AdminLoginController@index)
})
});
prefix : 路由前缀 对应生成的路由是 /Anime/login
match: http请求方式 get | post | delete
middleware : 中间件
中间件
1 要创建一个新的中间件,可以通过 Artisan 命令 make:middleware:
php artisan make:middleware CheckToken
2 生成文件的位置在 appHttpMiddlewareCheckToken.php
在 handle 方法里完成你的中间件 如:登录验证, 记录日志
handle分为 :中间件之前/之后
3 注册中间件
appHttpKernel.php
注册在 routeMiddleware 数组中:
<?php
namespace AppHttp;
use IlluminateFoundationHttpKernel 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 = [
IlluminateFoundationHttpMiddlewareCheckForMaintenanceMode::class,
IlluminateFoundationHttpMiddlewareValidatePostSize::class,
AppHttpMiddlewareTrimStrings::class,
IlluminateFoundationHttpMiddlewareConvertEmptyStringsToNull::class,
];
/**
* The application's route middleware groups.
*
* @var array
*/
## 中间件组
outes web => web.php api=> api.php 文件中所有的路由都必须通过中间件的处理
protected $middlewareGroups = [
'web' => [
AppHttpMiddlewareEncryptCookies::class,
IlluminateCookieMiddlewareAddQueuedCookiesToResponse::class,
IlluminateSessionMiddlewareStartSession::class,
// IlluminateSessionMiddlewareAuthenticateSession::class,
IlluminateViewMiddlewareShareErrorsFromSession::class,
AppHttpMiddlewareVerifyCsrfToken::class,
IlluminateRoutingMiddlewareSubstituteBindings::class,
AppHttpMiddlewareCheckToken::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' => IlluminateAuthMiddlewareAuthenticate::class,
'auth.basic' => IlluminateAuthMiddlewareAuthenticateWithBasicAuth::class,
'bindings' => IlluminateRoutingMiddlewareSubstituteBindings::class,
'can' => IlluminateAuthMiddlewareAuthorize::class,
'guest' => AppHttpMiddlewareRedirectIfAuthenticated::class,
'throttle' => IlluminateRoutingMiddlewareThrottleRequests::class,
'CheckToken' => AppHttpMiddlewareCheckToken::class,
];
}