Home  >  Article  >  Backend Development  >  Master the basics of Laravel middleware

Master the basics of Laravel middleware

PHPz
PHPzOriginal
2023-08-31 10:49:021092browse

掌握 Laravel 中间件的基础知识

In this article, we will take a deep dive into the Laravel framework to understand the concept of middleware. The first half of this article begins with an introduction to middleware and its practical uses.

As we continue, we will cover how to create custom middleware in a Laravel application. Once we've created our custom middleware, we'll explore the options available for registering it with Laravel so that it can actually be called during the request handling flow.

I hope you consider yourself familiar with basic Laravel concepts and the Artisan command line tool for generating scaffolding code. Of course, a working installation of the latest Laravel application allows you to immediately run the examples provided in this article.

What is middleware in Laravel?

We can think of middleware as a mechanism that allows you to connect to the typical request handling flow of a Laravel application. Typical Laravel route processing goes through certain stages of request processing, and middleware is one of the layers that the application must pass through.

So what’s the point of hooking up Laravel’s request processing process? Think about the things that need to be done in the early stages of application boot. For example, users need to be authenticated early on to decide whether they are allowed to access the current route.

Some things I can think of that can be achieved with middleware are:

  • Record request
  • Redirect user
  • Change/Clean incoming parameters
  • Manipulating responses generated by Laravel applications
  • there are more

In fact, the default Laravel application already comes with some important middleware. For example, there is middleware that checks if the site is in maintenance mode. On the other hand, there are middlewares to sanitize input request parameters. As I mentioned earlier, user authentication is also implemented through the middleware itself.

I hope the explanations so far have helped you feel more confident about the term middleware. If you're still confused, don't worry because we'll start building a custom middleware in the next section, which will help you understand exactly how to use middleware in the real world.

How to create custom middleware

In this section, we will create custom middleware. But what exactly is our custom middleware supposed to accomplish?

Recently, I came across a custom requirement from a client that if a user accesses the website from any mobile device, they should be redirected to the corresponding subdomain URL with all query string parameters remaining unchanged. I believe this is a perfect use case to demonstrate how to use Laravel middleware in this specific scenario.

The reason we want to use middleware in this case is that we need to hook into the application's request flow. In our custom middleware, we will check the user agent and if the user is on a mobile device, they will be redirected to the corresponding mobile URL.

After discussing all the theory, let’s start the actual development, this is the best way to understand a new concept, isn’t it?

As a Laravel developer, if you wish to create any custom functionality, you will end up using the Artisan tool most of the time to create basic template code. Let's use it to create basic template code for our custom middleware.

Go to the command line and go to the project's document root. Run the following command to create a custom middleware template MobileRedirect.

php artisan make:middleware MobileRedirect

This should create a file app/Http/Middleware/MobileRedirect.php with the following code.

<?php
 
namespace App\Http\Middleware;
 
use Closure;
 
class MobileRedirect
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        return $next($request);
    }
}

You will usually notice the implementation of the handle method, which acts as the backbone of the middleware and where the main logic of the middleware you want to implement should be located.

Take this opportunity to introduce the middleware types that come with Laravel. There are two main types: front middleware and post-middleware.

As the name suggests, before middleware is middleware that runs before the request is actually processed and the response is constructed. Post-middleware, on the other hand, runs after the request has been processed by the application, and the response has already been constructed by this time.

In our case, we need to redirect the user before processing the request, so it will be developed as a pre-middleware.

Go ahead and modify the file app/Http/Middleware/MobileRedirect.php with the following content.

<?php
 
namespace App\Http\Middleware;
 
use Closure;
 
class MobileRedirect
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        // check if the request is from mobile device
        if ($request->mobile == "1") {
            return redirect('mobile-site-url-goes-here');
        }
 
        return $next($request);
    }
}

For simplicity, we only check if the mobile query string parameter exists, if it is set to TRUE, the user will be redirected to the corresponding mobile device site URL . Of course, if you want real-time detection, you'll want to use a user-agent detection library.

Additionally, you will want to replace the mobile-site-url-goes-here route with the correct route or URL, as it is just a placeholder for demonstration purposes.

按照我们的自定义逻辑,调用 $next($request) 允许在应用程序链中进一步处理请求。在我们的例子中需要注意的重要一点是,我们将移动检测逻辑放置在 $next($request) 调用之前,有效地使其成为一个 before 中间件。

这样,我们的自定义中间件就几乎准备好进行测试了。目前,Laravel 无法了解我们的中间件。为此,您需要向 Laravel 应用程序注册您的中间件,这正是我们下一节的主题。

在进入下一部分之前,我想演示一下后中间件的外观,以防万一有人对此感到好奇。

<?php
 
namespace App\Http\Middleware;
 
use Closure;
 
class CustomMiddleWare
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $response = $next($request);
        
        /* your custom logic goes here */
        
        return $response;
    }
}

正如您已经注意到的,中间件的自定义逻辑在 Laravel 应用程序处理请求后执行。此时,您还可以访问 $response 对象,如果您愿意,它允许您操作它的某些方面。

这就是 after 中间件的故事。

我们的自定义中间件正在运行

本节描述了向 Laravel 应用程序注册中间件的过程,以便在请求处理流程中实际调用它。

继续打开文件 app/Http/Kernel.php 并查找以下代码片段。

/**
 * 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,
];

如您所见,$middleware 保存了 Laravel 默认安装附带的中间件数组。此处列出的中间件将根据每个 Laravel 请求执行,因此它是放置我们自己的自定义中间件的理想选择。

继续添加我们的自定义中间件,如以下代码片段所示。

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,
    \App\Http\Middleware\MobileRedirect::class,
];

现在,尝试使用查询字符串 mobile=1 访问任何 Laravel 路由,这应该会触发我们的中间件代码!

这就是您应该注册需要在每个请求上运行的中间件的方式。但是,有时您希望仅针对特定路由运行中间件。让我们检查一下如何使用 $routeMiddleware 来实现这一点。

在我们当前示例的上下文中,我们假设如果用户访问您网站上的任何特定路由,他们将被重定向到移动网站。在这种情况下,您不想将中间件包含在 $middleware 列表中。

相反,您希望将中间件直接附加到路由定义,如下所示。

Route::get('/hello-world', 'HelloWorldController@index')->middleware(\App\Http\Middleware\MobileRedirect::class);

事实上,我们可以更进一步,为我们的中间件创建一个别名,这样您就不必使用内联类名。

打开文件 app/Http/Kernel.php 并查找 $routeMiddleware ,它保存了别名到中间件的映射。让我们将我们的条目包含到该列表中,如以下代码片段所示。

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,
    'mobile.redirect' => \App\Http\Middleware\MobileRedirect::class
];

修改后的路由定义如下所示。

Route::get('/hello-world', 'HelloWorldController@index')->middleware('mobile.redirect');

这就是向 Laravel 应用程序注册中间件的故事。这非常简单,不是吗?

事实上,我们已经读到了本文的结尾,我希望您能充分享受它。

结论

探索任何框架中的架构概念总是令人兴奋的事情,这就是我们在本文中探索 Laravel 框架中的中间件时所做的事情。

从中间件的基本介绍开始,我们将注意力转移到在 Laravel 应用程序中创建自定义中间件的主题。文章的后半部分讨论了如何向 Laravel 注册自定义中间件,这也是探索附加中间件的不同方式的机会。

希望这次旅程富有成效,并且本文能够帮助您丰富您的知识。另外,如果您希望我在即将发表的文章中提出特定主题,您可以随时给我留言。

今天就这样,如果有任何疑问,请随时使用下面的提要来提出您的疑问!

The above is the detailed content of Master the basics of Laravel middleware. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn