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!

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values and handle functions that may return null values.

In PHP, use the clone keyword to create a copy of the object and customize the cloning behavior through the \_\_clone magic method. 1. Use the clone keyword to make a shallow copy, cloning the object's properties but not the object's properties. 2. The \_\_clone method can deeply copy nested objects to avoid shallow copying problems. 3. Pay attention to avoid circular references and performance problems in cloning, and optimize cloning operations to improve efficiency.

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.

Key players in HTTP cache headers include Cache-Control, ETag, and Last-Modified. 1.Cache-Control is used to control caching policies. Example: Cache-Control:max-age=3600,public. 2. ETag verifies resource changes through unique identifiers, example: ETag: "686897696a7c876b7e". 3.Last-Modified indicates the resource's last modification time, example: Last-Modified:Wed,21Oct201507:28:00GMT.

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

PHP is a server-side scripting language used for dynamic web development and server-side applications. 1.PHP is an interpreted language that does not require compilation and is suitable for rapid development. 2. PHP code is embedded in HTML, making it easy to develop web pages. 3. PHP processes server-side logic, generates HTML output, and supports user interaction and data processing. 4. PHP can interact with the database, process form submission, and execute server-side tasks.

PHP has shaped the network over the past few decades and will continue to play an important role in web development. 1) PHP originated in 1994 and has become the first choice for developers due to its ease of use and seamless integration with MySQL. 2) Its core functions include generating dynamic content and integrating with the database, allowing the website to be updated in real time and displayed in personalized manner. 3) The wide application and ecosystem of PHP have driven its long-term impact, but it also faces version updates and security challenges. 4) Performance improvements in recent years, such as the release of PHP7, enable it to compete with modern languages. 5) In the future, PHP needs to deal with new challenges such as containerization and microservices, but its flexibility and active community make it adaptable.

The core benefits of PHP include ease of learning, strong web development support, rich libraries and frameworks, high performance and scalability, cross-platform compatibility, and cost-effectiveness. 1) Easy to learn and use, suitable for beginners; 2) Good integration with web servers and supports multiple databases; 3) Have powerful frameworks such as Laravel; 4) High performance can be achieved through optimization; 5) Support multiple operating systems; 6) Open source to reduce development costs.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Zend Studio 13.0.1
Powerful PHP integrated development environment

SublimeText3 English version
Recommended: Win version, supports code prompts!

Dreamweaver CS6
Visual web development tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft