国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Table of Contents
What is middleware in Laravel?
How to create custom middleware
我們的自定義中間件正在運(yùn)行
結(jié)論
Home Backend Development PHP Tutorial Master the basics of Laravel middleware

Master the basics of Laravel middleware

Aug 31, 2023 am 10:49 AM

掌握 Laravel 中間件的基礎(chǔ)知識(shí)

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.

按照我們的自定義邏輯,調(diào)用 $next($request) 允許在應(yīng)用程序鏈中進(jìn)一步處理請(qǐng)求。在我們的例子中需要注意的重要一點(diǎn)是,我們將移動(dòng)檢測(cè)邏輯放置在 $next($request) 調(diào)用之前,有效地使其成為一個(gè) before 中間件。

這樣,我們的自定義中間件就幾乎準(zhǔn)備好進(jìn)行測(cè)試了。目前,Laravel 無(wú)法了解我們的中間件。為此,您需要向 Laravel 應(yīng)用程序注冊(cè)您的中間件,這正是我們下一節(jié)的主題。

在進(jìn)入下一部分之前,我想演示一下后中間件的外觀,以防萬(wàn)一有人對(duì)此感到好奇。

<?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;
    }
}

正如您已經(jīng)注意到的,中間件的自定義邏輯在 Laravel 應(yīng)用程序處理請(qǐng)求后執(zhí)行。此時(shí),您還可以訪問(wèn) $response 對(duì)象,如果您愿意,它允許您操作它的某些方面。

這就是 after 中間件的故事。

我們的自定義中間件正在運(yùn)行

本節(jié)描述了向 Laravel 應(yīng)用程序注冊(cè)中間件的過(guò)程,以便在請(qǐng)求處理流程中實(shí)際調(diào)用它。

繼續(xù)打開文件 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,
];

如您所見(jiàn),$middleware 保存了 Laravel 默認(rèn)安裝附帶的中間件數(shù)組。此處列出的中間件將根據(jù)每個(gè) Laravel 請(qǐng)求執(zhí)行,因此它是放置我們自己的自定義中間件的理想選擇。

繼續(xù)添加我們的自定義中間件,如以下代碼片段所示。

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

現(xiàn)在,嘗試使用查詢字符串 mobile=1 訪問(wèn)任何 Laravel 路由,這應(yīng)該會(huì)觸發(fā)我們的中間件代碼!

這就是您應(yīng)該注冊(cè)需要在每個(gè)請(qǐng)求上運(yùn)行的中間件的方式。但是,有時(shí)您希望僅針對(duì)特定路由運(yùn)行中間件。讓我們檢查一下如何使用 $routeMiddleware 來(lái)實(shí)現(xiàn)這一點(diǎn)。

在我們當(dāng)前示例的上下文中,我們假設(shè)如果用戶訪問(wèn)您網(wǎng)站上的任何特定路由,他們將被重定向到移動(dòng)網(wǎng)站。在這種情況下,您不想將中間件包含在 $middleware 列表中。

相反,您希望將中間件直接附加到路由定義,如下所示。

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

事實(shí)上,我們可以更進(jìn)一步,為我們的中間件創(chuàng)建一個(gè)別名,這樣您就不必使用內(nèi)聯(lián)類名。

打開文件 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 應(yīng)用程序注冊(cè)中間件的故事。這非常簡(jiǎn)單,不是嗎?

事實(shí)上,我們已經(jīng)讀到了本文的結(jié)尾,我希望您能充分享受它。

結(jié)論

探索任何框架中的架構(gòu)概念總是令人興奮的事情,這就是我們?cè)诒疚闹刑剿?Laravel 框架中的中間件時(shí)所做的事情。

從中間件的基本介紹開始,我們將注意力轉(zhuǎn)移到在 Laravel 應(yīng)用程序中創(chuàng)建自定義中間件的主題。文章的后半部分討論了如何向 Laravel 注冊(cè)自定義中間件,這也是探索附加中間件的不同方式的機(jī)會(huì)。

希望這次旅程富有成效,并且本文能夠幫助您豐富您的知識(shí)。另外,如果您希望我在即將發(fā)表的文章中提出特定主題,您可以隨時(shí)給我留言。

今天就這樣,如果有任何疑問(wèn),請(qǐng)隨時(shí)使用下面的提要來(lái)提出您的疑問(wèn)!

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 of this Website
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

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How do I stay up-to-date with the latest PHP developments and best practices? How do I stay up-to-date with the latest PHP developments and best practices? Jun 23, 2025 am 12:56 AM

TostaycurrentwithPHPdevelopmentsandbestpractices,followkeynewssourceslikePHP.netandPHPWeekly,engagewithcommunitiesonforumsandconferences,keeptoolingupdatedandgraduallyadoptnewfeatures,andreadorcontributetoopensourceprojects.First,followreliablesource

What is PHP, and why is it used for web development? What is PHP, and why is it used for web development? Jun 23, 2025 am 12:55 AM

PHPbecamepopularforwebdevelopmentduetoitseaseoflearning,seamlessintegrationwithHTML,widespreadhostingsupport,andalargeecosystemincludingframeworkslikeLaravelandCMSplatformslikeWordPress.Itexcelsinhandlingformsubmissions,managingusersessions,interacti

How to set PHP time zone? How to set PHP time zone? Jun 25, 2025 am 01:00 AM

TosettherighttimezoneinPHP,usedate_default_timezone_set()functionatthestartofyourscriptwithavalididentifiersuchas'America/New_York'.1.Usedate_default_timezone_set()beforeanydate/timefunctions.2.Alternatively,configurethephp.inifilebysettingdate.timez

How do I validate user input in PHP to ensure it meets certain criteria? How do I validate user input in PHP to ensure it meets certain criteria? Jun 22, 2025 am 01:00 AM

TovalidateuserinputinPHP,usebuilt-invalidationfunctionslikefilter_var()andfilter_input(),applyregularexpressionsforcustomformatssuchasusernamesorphonenumbers,checkdatatypesfornumericvalueslikeageorprice,setlengthlimitsandtrimwhitespacetopreventlayout

What are the best practices for writing clean and maintainable PHP code? What are the best practices for writing clean and maintainable PHP code? Jun 24, 2025 am 12:53 AM

The key to writing clean and easy-to-maintain PHP code lies in clear naming, following standards, reasonable structure, making good use of comments and testability. 1. Use clear variables, functions and class names, such as $userData and calculateTotalPrice(); 2. Follow the PSR-12 standard unified code style; 3. Split the code structure according to responsibilities, and organize it using MVC or Laravel-style catalogs; 4. Avoid noodles-style code and split the logic into small functions with a single responsibility; 5. Add comments at key points and write interface documents to clarify parameters, return values ??and exceptions; 6. Improve testability, adopt dependency injection, reduce global state and static methods. These practices improve code quality, collaboration efficiency and post-maintenance ease.

What is data serialization in PHP (serialize(), unserialize())? What is data serialization in PHP (serialize(), unserialize())? Jun 22, 2025 am 01:03 AM

ThePhpfunctionSerialize () andunserialize () AreusedtoconvertcomplexdaTastructdestoresintostoraSandaBackagain.1.Serialize () c OnvertsdatalikecarraysorobjectsraystringcontainingTypeandstructureinformation.2.unserialize () Reconstruct theoriginalatataprom

How do I embed PHP code in an HTML file? How do I embed PHP code in an HTML file? Jun 22, 2025 am 01:00 AM

You can embed PHP code into HTML files, but make sure that the file has an extension of .php so that the server can parse it correctly. Use standard tags to wrap PHP code, insert dynamic content anywhere in HTML. In addition, you can switch PHP and HTML multiple times in the same file to realize dynamic functions such as conditional rendering. Be sure to pay attention to the server configuration and syntax correctness to avoid problems caused by short labels, quotation mark errors or omitted end labels.

How do I execute SQL queries using PHP? How do I execute SQL queries using PHP? Jun 24, 2025 am 12:54 AM

Yes,youcanrunSQLqueriesusingPHP,andtheprocessinvolveschoosingadatabaseextension,connectingtothedatabase,executingqueriessafely,andclosingconnectionswhendone.Todothis,firstchoosebetweenMySQLiorPDO,withPDObeingmoreflexibleduetosupportingmultipledatabas

See all articles