Laravel中间件

本文概述

  • 创建一个中间件
  • 应用中间件
  • 检查中间件的条件
中间件充当用户和请求之间的层。这意味着, 当用户请求服务器时, 请求将通过中间件, 然后中间件将验证请求是否已通过身份验证。如果用户的请求已通过身份验证, 则该请求将发送到后端。如果用户请求未通过身份验证, 则中间件会将用户重定向到登录屏幕。
除身份验证外, 其他中间件可用于执行各种任务。例如, CORS中间件负责将标头添加到所有响应。
【Laravel中间件】Laravel框架包括一些中间件, 例如身份验证和CSRF保护, 所有这些都位于app / Http / Middleware目录中。
我们可以说中间件是一个http请求过滤器, 你可以在其中检查条件。
在中间件中, 我们将讨论以下主题:
  • 制作中间件
  • 应用中间件
  • 检查中间件的条件
  • 路由中间件
创建一个中间件 输入命令php artisan make:middleware’ 中间件名称’ 。
Laravel中间件

文章图片
在上面的屏幕中, 我们键入命令“ php artisan make:middleware CheckAge”, 其中CheckAge是中间件的名称。上面的窗口显示已成功创建名称为“ CheckAge”的中间件。
要查看是否已创建CheckAge中间件, 请转到你的项目。我们的项目名称为laravelproject, 因此中间件的路径为:C:\ xampp \ htdocs \ laravelproject \ app \ Http \ Middleware。
Laravel中间件

文章图片
应用中间件 中间件可以应用于所有URL或某些特定的URL。
让我们将中间件应用于所有URL。
步骤1:打开kernel.php文件。如果我们想将中间件应用于所有URL, 则在中间件数组中添加中间件的路径。
< ?phpnamespace 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 yourapplication.** @var array*/ protected $middleware = [ \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class, \Illuminate\Foundation\Http \Middleware\ValidatePostSize::class, \App\Http\Middleware\TrimStrings::class, \App\Http\Middleware\CheckAge::class, \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class, ]; /*** The application's route middleware groups.** @var array*/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' => ['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, ]; }

步骤2:在Git Bash窗口中键入php artisan serve命令。
Laravel中间件

文章图片
步骤3:打开你已创建为中间件的CheckAge.php文件。
< ?phpnamespace App\Http\Middleware; use Closure; class CheckAge{/*** Handle an incoming request.** @param\Illuminate\Http \Request$request* @param\Closure$next* @return mixed*/public function handle($request, Closure $next) { //return "middleware"; echo "hello world"; return $next($request); }}

步骤4:现在, 输入URL’ http:// localhost / laravelproject / public /’ 。
Laravel中间件

文章图片
让我们将中间件应用于某些特定的路由。
步骤1:打开kernel.php文件。如果我们要将中间件应用于某些特定的路由
< ?phpnamespace 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 yourapplication.** @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*/ 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' => ['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, 'age' => \App\Http\Middleware\CheckAge::class ]; }

在上面的代码中, 我们添加了代码, 即“ age” => \ App \ Http \ Middleware \ CheckAge :: class’ , 其中age是中间件的名称。现在, 我们可以将“年龄”中间件用于某些特定的路由。
步骤2:打开你已创建为中间件的CheckAge.php文件。
步骤3:在web.php文件中添加中间件代码。
Route::Get('/', function(){return view('welcome'); })-> middleware('age'); Route::Get('user/profile', function(){return "user profile"; });

在上面的代码中, 我们在’ /’ 根URL中添加了中间件, 而在’ user / profile’ URL中未添加中间件。
输出:
当我们访问根URL时, 输出将是:
Laravel中间件

文章图片
上面的输出表明, 中间件代码在显示“ hello world”时也已被访问。
当我们访问URL(即/ user / profile)时, 输出为:
Laravel中间件

文章图片
上面的输出表明尚未访问中间件代码。
在URL中传递参数时。
web.php
Route::Get('/{age}', function($age){return view('welcome'); })-> middleware('age');

CheckAge.php
< ?phpnamespace App\Http\Middleware; use Closure; class CheckAge{ /** * Handle an incoming request. ** @param\Illuminate\Http\Request$request * @param\Closure$next * @return mixed */public function handle($request, Closure $next) { //return "middleware"; echo "this is checkage middleware"; return $next($request); }}

输出量
Laravel中间件

文章图片
检查中间件的条件 中间件也可用于检查条件。让我们通过一个例子来理解。
Route::Get('/{age}', function($age){return view('welcome'); })-> middleware('age');

< ?phpnamespace App\Http\Middleware; use Closure; class CheckAge{/*** Handle an incoming request.** @param\Illuminate\Http\Request$request * @param\Closure$next* @return mixed*/ public function handle($request, Closure $next){//return "middleware"; if($request-> age> 10){echo "Age is greater than 10"; }else{echo"Age is not greater than 10"; }return $next($request); }}

输出:
Laravel中间件

文章图片
Laravel中间件

文章图片

    推荐阅读