路由中间件是用户和请求的中间层。通过用户登录来说明,这意味着当用户请求服务器时,请求将先通过中间件,然后中间件验证请求是否经过身份验证,如果用户的请求通过了身份验证,则该请求被发送到后端。 如果用户请求未通过身份验证,则中间件会将用户重定向到登录页面。
laravel中间件可用于参数校验,CSRF,权限校验等。这些中间件都位于 app/Http/Middleware 目录下。
以下讲解laravel中间件的创建和使用方法。
创建中间件
命令如下:
php artisan make:middleware '中间件名'
上面的例子中创建了一个CheckAge
的中间件名称。要查看是否创建成功,可以转到中间件的路径
d:\test\yxjc123\app\Http\Middleware
查看CheckAge.php文件是否生成。
使用中间件
中间件作用于所有的url路由。
1. 打开kernel.php 文件(D:\test\yxjc123\app\Http\Kernel.php)。在 middleware 和 routeMiddleware 数组中添加 CheckAge
类,完整代码如下。
<?php
namespace App\Http;
use App\Http\Middleware\CheckAge;
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<int, class-string|string>
*/
protected $middleware = [
// \App\Http\Middleware\TrustHosts::class,
\App\Http\Middleware\TrustProxies::class,
\Fruitcake\Cors\HandleCors::class,
\App\Http\Middleware\PreventRequestsDuringMaintenance::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\App\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
CheckAge::class
];
/**
* The application's route middleware groups.
*
* @var array<string, array<int, class-string|string>>
*/
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,
],
'api' => [
// \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
'throttle:api',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
];
/**
* The application's route middleware.
*
* These middleware may be assigned to groups or used individually.
*
* @var array<string, class-string|string>
*/
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,
'checkAge' => CheckAge::class
];
}
2.定义一个路由 Route::get('/', function () {
return view('welcome');
});
3.启动服务php artisan serve
并访问地址 127.0.0.1:8000如图所示,中间件已生效。
中间件作用于某些特定的路径地址
1. 和上面一样,打开kernel.php 文件(D:\test\yxjc123\app\Http\Kernel.php)。在routeMiddleware 数组中添加 CheckAge类。
2. 打开刚才创建的中间件文件CheckAge.php
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
class CheckAge
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse) $next
* @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
*/
public function handle(Request $request, Closure $next)
{
echo "checkAge";//todo 判断
return $next($request);
}
}
3. 在路由文件web.php文件中增加中间件代码。
Route::get('/', function () {
return view('welcome');
})-> middleware('checkAge');
Route::Get('/test',function()
{
return "test";
});
最后在浏览器地址 栏中输入http://127.0.0.1:8000/test
http://127.0.0.1:8000/
返回的结果不一样,因为中间件只作用了路径/没有作用于/test。
中间件参数校验
中间件也可以进行参数校验。 让我们通过下面的例子来理解。
Route::Get('/{age}',function($age)
{
return view('welcome');
})-> middleware('checkAge');
打开刚才创建的中间件文件CheckAge.php <?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
class CheckAge
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse) $next
* @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
*/
public function handle(Request $request, Closure $next)
{
//echo "checkAge";
if($request->age>10)
{
return response()->json(['error' => "check age error !"], 501);
}
return $next($request);
}
}
上面的例子中,我们判断年龄是否大于10,如果是则返回错误信息。