Middleware acts as a layer between the user and the request. It means that when the user requests the server then the request will pass through the middleware, and then the middleware verifies whether the request is authenticated or not. If the user's request is authenticated then the request is sent to the backend. If the user request is not authenticated, then the middleware will redirect the user to the login screen.
An additional middleware can be used to perform a variety of tasks except for authentication. For example, CORS middleware is responsible for adding headers to all the responses.
Laravel framework includes several middleware such as authentication and CSRF protection, and all these are located in the app/Http/Middleware directory.
We can say that middleware is an http request filter where you can check the conditions.
In middleware, we are going to discuss the following topics:
Creating a middleware
Type the command php artisan make:middleware 'name of the middleware'.
In the above screen, we type the command "php artisan make:middleware CheckAge" where CheckAge is the name of the middleware. The above window shows that the middleware has been created successfully with the name "CheckAge".
To see whether the CheckAge middleware is created or not, go to your project. Our project name is laravelproject, so the path for the middleware would be: C:\xampp\htdocs\laravelproject\app\Http\Middleware.
Apply a Middleware
Middleware can be either applied to all the URLs or some particular URLs.
Let's apply the middleware to all the URLs.
Step 1: Open the kernel.php file. If we want to apply the middleware to all the URLs, then add the path of the middleware in the array of middleware.
Step 2: Type the command php artisan serve in Git Bash Window.
Step 3: Open the CheckAge.php file, which you have created as a middleware.
Step 4: Now, enter the URL 'http://localhost/laravelproject/public/'.
Let's apply the middleware to some specific routes.
Step 1: Open the kernel.php file. If we want to apply the middleware to some specific routes
In the above code, we have added the code, i.e., ''age' => \App\Http\Middleware\CheckAge::class', where age is the name of the middleware. Now, we can use the 'age' middleware for some specific routes.
Step 2: Open the CheckAge.php file, which you have created as a middleware.
Step 3: Add the middleware code in the web.php file.
In the above code, we have added middleware in '/' root URL, and we have not added the middleware in the 'user/profile' URL.
When we access the root URL, then the output would be:
The above output shows that the middleware code has also been accessed as it is displaying a "hello world".
When we access the URL, i.e., /user/profile, then the output would be:
The above output that the middleware code has not been accessed.
When the parameter is passed in a URL.
Check condition in middleware
Middleware can also be used to check the condition. Let's understand through an example.