What is middleware? And how to create a middleware in the Laravel framework
In this article, we are going to talk about middleware and how to create middleware in the Laravel framework.
In this article, we are going to talk about middleware and how to create middleware in the Laravel framework. We will talk about the following topics.
- What is middleware?
- Why and where to use middleware?
- What does middleware do in Laravel?
- How to create a middleware in Laravel?
- How to register a middleware in Laravel?
What is middleware?
Middleware is software or a layer of software that carries out the task of transferring information between programs and services of two or one system that consist of different parts. In simpler words, middleware is software that provides services to other software.
Middleware allows developers to focus on achieving the specific goal of their program and use that to do things related to the input and output of the program more easily.
The word Middleware was first used in a programming event called “NATO Software Engineering Conference 1968” in Germany.
If we liken the software to the core of the earth, to access it, we have to go through the entire crust of the earth to reach it. In this example, the earth’s crust plays the role of middleware. Each layer grants or denies access to the next layer. This will continue until we don’t have access to the application, which means we have to go through all the middleware to complete a request!
Maybe this is a little vague and confusing for you! But wait until the end to learn more about middleware!
Why and where to use middleware?
One of the reasons we use middleware is to simplify the communication process through middleware. Middleware has different capabilities. Some middleware in cloud systems communicates between the user and the system or the software and the database. Others examine specific operations and conditions in HTTP communications.
In general, we use middleware when we want to connect separate systems without making changes to either part.
What does middleware do in Laravel?
In Laravel or similar systems, the middleware does some of the work for us and filters HTTP requests coming to the software.
For example, we can create a middleware that only users whose gender is (woman) can go through and receive a response, otherwise, an error will occur.
Or another example, we can create a middleware that stores HTTP requests for us in a database or file so that we can better control the operations of our software. This middleware can store the input request and the output response in a database like MongoDB (Note: in the next story, we will create a middleware to store and log the requests and responses of the Laravel application).
How to create a middleware in Laravel?
To create middleware in Laravel you must run the following command:
php artisan make:middleware [your middleware name]
for example, to create a middleware to determine the gender of users, we run the following command in the CLI
php artisan make:middleware GenderCheckMiddleware
This command will create a new class named GenderCheckMiddleware in the app/Http/Middleware directory (This directory is the location of middleware in Laravel) which is as follows:
By default, there is a function called the handle in the created class. In this function, we check our desired terms and conditions and if the request meets the desired conditions, it will be allowed to go to the next step, otherwise, the request will be stopped.
Now we assume that the user fills in a parameter form called gender, which contains the values [man, woman].
If the gender value is equal to [woman], our middleware will allow the request to continue, otherwise, the user will receive a 403 error.
We will change the handle function of our middleware as follows:
In this function, we have checked if the gender value in the request is not equal to women We will show a 403 error meaning no access to the user. otherwise, “return $next($request);” It will move the user to the next layer
How to register a middleware in Laravel?
Now we have created our middleware. Now we want to register it in Laravel so that we can use it wherever we need it.
In Laravel, to register a middleware, you must register it in the list of middleware in the app/Http/Kernel.php file. There is 3 property in this class:
1- Global Middleware:
If you want a middleware to run on all HTTP requests. Put your middleware class in the $middleware list.
For example, if you want to run GenderCheckMiddleware on all requests and check gender conditions. Just list the class in the $middleware attribute.
2- Routes Middleware
If you want to assign your middleware to certain routes, you must list it in the $routeMiddleware attribute of the app/Http/Kernel.php class.
You can add your middleware to this list by defining a key. For example, we have added the created middleware to the $routeMiddleware list with the [gender.check] key.
To assign middleware to a specific route in Laravel, we use the middleware() function.
For example, you want to assign the GenderCheckMiddleware middleware defined in $routeMiddleware with the name [gender.check] to a specific route. For this, we proceed as follows.
Route::post('/user/store', function () {
//
})->middleware('gender.check');
You can also assign multiple middlewares to a specific route:
Route::post('/user/store', function () {
//
})->middleware(['gender.check', 'auth', 'signed']);
3- Middleware Groups
Sometimes you may have several middlewares that you want to assign to your routes together. In these cases, you can use the $middlewareGroups property that is defined in app/Http/Kernel.php.
By default, Laravel has created two groups of middleware called api and web in this property.
You can also create group middlewares of your routes.
For example, in the image below, we have created a middleware group called to [check], which includes 3 middleware.
You can also use the middleware() function below to use a group middleware as needed.
Route::get('/', function () {
//
})->middleware('check');
Remember that by default, the web group middleware and api are assigned to the api group and web routes in App\Providers\RouteServiceProvider by Laravel.
Conclusion:
We learned in this story that there are different middleware. In Laravel, we can use middleware to filter HTTP requests.
By default, Laravel has multi middleware, but we can create our middleware simply with Laravel’s artisan.
In the middleware, we can check a certain condition, add or subtract a certain amount to the request, or even log requests.
I hope you enjoyed this article!
In the next article, I will create a middleware to log HTTP requests and responses in a Laravel application.
Follow me if you are interested :)