Laravel 中间件

Laravel 中间件

中间件作为用户和请求之间的一层。这意味着当用户请求服务器时,请求会经过中间件,然后中间件验证请求是否已经认证。如果用户请求已经认证,请求会被发送到后端。如果用户请求未经认证,那么中间件会将用户重定向到登录界面。

另外一个中间件可以用于执行各种任务,除了认证之外。例如,CORS中间件负责在所有的响应中添加头部。

Laravel 框架包含多个中间件,例如身份验证和CSRF保护,它们都位于 app/Http/Middleware 目录下。

我们可以说中间件是一个 HTTP 请求过滤器,您可以在其中进行条件检查。

在中间件中,我们将讨论以下主题:

  • 创建一个中间件
  • 应用中间件
  • 在中间件中检查条件
  • 路由中间件

创建一个中间件

输入以下命令 php artisan make:middleware ‘中间件名称’

Laravel 中间件

要查看是否已创建 CheckAge 中间件,请转到您的项目。我们的项目名称是 laravelproject,因此中间件的路径将为: C:\xampp\htdocs\laravelproject\app\Http\Middleware

Laravel 中间件

应用中间件

中间件可以应用于所有URL或某些特定URL。

让我们把中间件应用于所有URL。

步骤1: 打开kernel.php文件。如果我们想要应用中间件于所有URL,那么将中间件的路径添加到中间件数组中。

<?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,
 \App\Http\Middleware\CheckAge
::class,
  \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
    ];

   /**
     * The application's route middleware groups.
     *
     * @var array
     */

protectedmiddlewareGroups = [
        '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 文件。

<?php

namespace App\Http\Middleware;

use Closure;

class CheckAge

{

/**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http 
\Request  request
     * @param  \Closurenext
     * @return mixed
     */
  public function handle(request, Closurenext)
 {
 //return "middleware";
echo "hello world";
return next(request);
}
}

步骤4: 现在,输入网址 ‘ http://localhost/laravelproject/public/ ‘。

Laravel 中间件

让我们将中间件应用于一些特定的路由。

步骤1: 打开kernel.php文件。如果我们想要将中间件应用于一些特定的路由

<?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
     */
 protectedmiddlewareGroups = [
 '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是中间件的名称。现在,我们可以在一些特定的路由中使用’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');

检查年龄.php

<?php
namespace App\Http\Middleware;
use Closure;
class CheckAge
{
 /**
 * Handle an incoming request.
 *

* @param
  \Illuminate\Http\Request  request
 * @param  \Closurenext
 * @return mixed
 */
  public function handle(request, Closurenext)
 {
 //return "middleware";
echo "this is checkage middleware";
return next(request);
}}

输出

Laravel 中间件

在中间件中检查条件

中间件也可以用来检查条件。让我们通过一个例子来理解。

Route::Get('/{age}',function($age)
{
  return view('welcome');
})-> middleware('age');
<?php
namespace App\Http\Middleware;
use Closure;
class CheckAge
{

/**
     * Handle an incoming request.
     *

* @param
  \Illuminate\Http\Request  request

 * @param  \Closurenext
     * @return mixed
     */

   public function handle(request, Closurenext)

{
  //return "middleware";
if(request->age>10)
{
echo "Age is greater than 10";
}
else
{
echo"Age is not greater than 10";
}
returnnext($request);

}}

输出:

Laravel 中间件

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程