Home >>Laravel Tutorial >Laravel Middleware

Laravel Middleware

Laravel Middleware

Middleware in Laravel behaves as a layer between the user and the request. It simply means that whenever the user requests to the server, the request is passed through the middleware and then the middleware verifies whether the authentication of the request. After the user's request is authenticated then the request of the user is sent to the backend. Suppose the user’s request is denied authentication, then the middleware will simply redirect the user to the login screen.

An additional middleware can also be used to execute a variety of tasks except for authentication. For example, CORS middleware is only responsible for adding the headers to all the responses.

Laravel framework consists of various middleware like authentication and CSRF protection. Please note that these are located at the location app/Http/Middleware directory.

It can be also be understood in this way that middleware is basically an Http request filter where the conditions are checked.

These are the following topics that will be discussed in this middleware tutorial:

  • Create a middleware
  • Apply the middleware
  • Check condition in middleware
  • Route middleware

Creating a middleware in Laravel

In an example, where the command "php artisan make: middleware DemoTest" is typed where DemoTestis the name of the middleware. You will see that the middleware created successfully with the name "DemoTest".

In order to check whether the DemoTest middleware is created or not, simply go to your project. Since we have named our project laravelproject hence, the path for the middleware is: C:\xampp\htdocs\laravelproject\app\Http\Middleware.


No Sidebar ads