Hello Laravel Friends,

In this Laravel tutorial, we will learn about Middleware in Laravel 8 with an example. First, let’s start by understanding the meaning of middleware in Laravel.

What is Middleware in Laravel?

Middleware is a type of filtering mechanism for HTTP requests in Laravel. It acts as an intermediary between the user request and response. 

For example, Laravel middleware verifies whether your application’s user is authenticated or not. If the user is not authenticated, the middleware will redirect the user to your application’s login screen. However, if the user is authenticated, the middleware will allow the request to move further into the application.

Create Middleware

Use the below command to create middleware.

The file will be created in this path app/Http/Middleware directory.

Create UserAuthenticated Middleware

Run the below command to create UserAuthenticated middleware

Now add your logic

Registering Middleware

We need to register every middleware before using it. There are two types of middleware.

1. Global Middleware

Global middlewares are those that will be running during every HTTP request of your application. In the $middleware property of your app/Http/Kernel.php class, you can list all the global middleware for your project.

2. Route Middlewares

If you would like to assign middleware to specific routes, you should first assign the middleware a key in your app/Http/Kernel.php file. By default, the $routeMiddleware property of this class contains entries for the middleware included with Laravel. You may add your own middleware to this list and assign it a key of your choice.

Assign Middleware to Route

After defining the middleware in the HTTP kernel, you can use the middleware method to assign middleware to a route.

Also, you assign multiple middlewares to the route. 


This was all about middleware in Laravel 8. If you have any doubts, you can connect with our Laravel developers, who will help you provide solutions for your difficulties. Stay in touch with us for more Laravel tutorials.

Happy Coding!

Click to rate this post!
[Total: 7 Average: 4]