Laravel Framework – Middleware

What is middleware?

In the Laravel framework, middleware is a component used to handle HTTP requests. It allows you to execute some code logic before or after the request enters routing processing.

Advantages and functions of middleware

Handle authentication: verify that the user is logged in or check if the user has permission to access a specific route

Logging: Record the log of the request to understand the trajectory of the request.

Access control: Ensure requests are sent from specified IP addresses or restricted to specific user groups.

Data validation: Verify that the requested data conforms to the specified format.

Data processing: Perform processing on the requested data, such as encoding the data or encrypting the data.

Caching: Middleware can use caching to improve the speed and efficiency of requests.

Security: Middleware can prevent security vulnerabilities such as cross-site request forgery (CSRF) attacks.

Permission control: Middleware can control user access permissions to ensure security.

Authentication: Middleware can implement authentication and authorization logic.

We’ll show you four examples of uses below! ! ! ! !

Creation and use of middleware

1, create middleware

Use the make:middleware command to create new middleware:

php artisan make:middleware CheckAge

If you are a novice, please first move to Middleware | Basic Functions | “Laravel 7 Chinese Documentation 7.x” | Laravel China community welcome back after understanding.

2, modify middleware

Path address: app\Http\Middleware\Middleware file you created:
 public function handle(Request $request, Closure $next)
    {
\t\t
// Code executed before the request enters routing processing
        // You can perform some processing or inspection on the request here, and then decide whether to continue routing processing

        // For example, you can check here if the user is logged in and redirect to the login page if not
\t\t

        //Execute the next middleware or route handler
        return $next($request);
    }

3, registration middleware:

Path address: app/Http/Kernel.php registration middleware

Find the middleware array and routeMiddleware array . Add the following code to the middleware array:

3.1 Register global middleware

Registering global middleware is as simple as $middleware in the app/Http/Kernel.php file Just list this middleware in the properties

protected $middleware = [
    // ...
    \App\Http\Middleware\ExampleMiddleware::class,
];

3.2 Register routing middleware

Write it under $routeMiddleware.

protected $routeMiddleware = [
    // ...
    'example.middleware' => \App\Http\Middleware\ExampleMiddleware::class,
];

4, use middleware:

Route::get('/example', 'ExampleController@index')->middleware('example.middleware');
//When accessing the /example route, the ExampleMiddleware middleware will be executed first. 

Some functional code examples of middleware

What is access control?

Access control: You can use middleware to ensure that requests are sent from specified IP addresses or are restricted to specific user groups.

Here are the test results:

Under 18 years old Unauthorized

If you are 18 or above, you are welcome!

The above code implements a middleware that checks the age field in the request. If the age is less than 18, an error message will be returned indicating that the request is not authorized.

Laravel middleware logging!

Logging effect

Now, each time a request is processed, the requested information is logged. You can view request logs in the storage/logs directory.

By using middleware to record request logs, you can easily understand the trace of the request, and if an error occurs, you can also use the log to debug the problem.

Laravel middleware data verification!

Test effect

fail

We used Laravel’s Validator class for verification, creating a validator by calling the make method and passing in the request data and validation rules.

If verification fails, a JSON response with a 400 status code and error information is returned.

If the verification passes, continue executing the request by calling the $next method and passing in the request.

Laravel middleware data processing

Encrypted data

Encrypt the data in the request. We used the encryptData method to encrypt the data, and the specific implementation of this method is in it.

When a request passes through this middleware, it processes the data in the request, rewrites the processed data into the request, and finally returns the request for continued processing.

10 middleware issues worth thinking about

Understanding and defining middleware?

Please see the top of the article

Can you explain in detail how to use Laravel middleware?

Use the Artisan command line tool to generate middleware and register middleware. Modify the generated middleware file. Use middleware

How do you use middleware in development?

Create middleware, register middleware, distribute middleware and then use it as needed

What are the advantages and functions of middleware?

Please see the top of the article

How to customize a middleware?

Generate middleware using Artisan command line tools

How to use middleware as a part of request processing?

In Laravel, middleware can be added as a part of request processing by adding middleware to the life cycle of an HTTP request. To use middleware as part of request processing, you need to perform the following steps:

Create middleware: Use the Laravel command line tool to create middleware.

Register middleware: Register middleware during the application’s HTTP request lifecycle.

Define middleware processing logic: Define processing logic in the middleware class.

Assign middleware: Assign middleware in a route or controller to specify its role on a specific request.

Laravel preprocesses requests before they flow through middleware. After the middleware handles the request, if the middleware allows the request to continue, the request will continue to the next link. If the middleware does not allow the request to continue, the request will be terminated. Therefore, middleware can control the processing of requests by controlling the flow of requests.

Does the middleware support sharing data across requests?

Middleware can support sharing data across requests. But how it’s implemented depends on the web framework and language used.

For example, in the Laravel framework, session storage can be used to share data across multiple requests. Additionally, data can be shared using global variables or cache storage

How does middleware control the flow of requests?

Middleware can control the flow of requests by preprocessing them and deciding whether to continue delivering the request or response. Middleware implements request control by checking the status or content of the request and performing corresponding processing.

For example, in Laravel, you can use middleware to check if the user is logged in, and if not, do not pass the request and redirect the user to the login page. In addition, middleware can be used to check whether the user has the specified permissions and block the flow of the request if necessary.

Therefore, by using middleware, you can control the flow of requests, ensuring application security and data consistency.

Can you give an example of using middleware in a real project?

I once wrote about the access rights of middleware in the backend rental management. Determine based on the access users and permissions. If not, intercept. The advantage of this is that it can ensure the security of our rental system management backend and greatly improve the security performance

Reference URL:

laravel Chinese manual

Explore the power of Laravel middleware: Understand its capabilities and benefits

syntaxbug.com © 2021 All Rights Reserved.