Updated April 11, 2023
Introduction to Laravel Middleware
When a user wishes to use your application and there is an HTTP request from the user’s side, middleware provides the amenities to authenticate the request. It filters the HTTP requests that come to your application and redirects the user to the particular login page from where the user can proceed using the app after authenticating one’s identity. Besides authentication several other important tasks also can be performed by additional middleware in Laravel. There are CORS middleware and logging middleware which perform their respective duties other than authentication. Every of the middleware is registered and saved in the directory – app/Http/Middleware.
What is Laravel Middleware?
Laravel Middleware is primarily a bridge between the request and the response. The user who wishes to get access to the application and the processes in it has to make sure that the request is created for the appropriate response from the application and Middleware deliberates this response for the benefit of the user who has put across a request. Ideally the programming done enables the middleware to direct the user to the login page to add in the login credentials and this is a highly important security concern to avoid unauthorized people from accessing the data that is supposed to be made available to only those who can log in. Laravel Middleware depending upon the request that comes in directs the user either to the Login page or the Home page.
Laravel Middleware is created and registered and then it is attached to a route. In this way it is got ready to function according to the need. Middleware is an essential component of the Laravel framework as it plays an important role in security for the data and the safety of the content in the application. The filtering of HTTP requests which is an important task is specifically the main function of middleware. The benefit that Laravel provides is that one can easily customize a middleware according to the need of the application that is getting made in the Laravel framework. The process of coordination between the request and the response is a task and middleware has all the capacity to handle it and you can be assured that no errors would emerge in its functioning regularly. The syntax that is used for the creation of middleware is as follows:
Php artisan make: middleware<middleware_name>
How does Laravel Middleware work?
Middlewares are used in different circumstances like:
- Service call’s rate-limiting.
- If you are building an API, then allowing the confirmation of the API key incoming route request.
- The language alteration or change depending upon the local language in dominance.
The confirmation of whether the middleware will function before or after the request is dependent upon the middleware settings arranged by the user in a command. The two types of middleware provided by Laravel are:
- Global Middleware
- Route Middleware
When there is an HTTP request, Global middleware starts responding to the requests. You can keep a record of all the global middleware components in the class app/Http/Kernel.php. When you add a key along with the middleware, it can be routed to the desired specific location/route. All the entries are stored in the $routeMiddleware section. When you add a custom made middleware, you also need to add a key of your choice to get in enabled.
There is a possibility of passing parameters to middlewares too. When there are several attributes in your application like employees, administrator, owner, customer, client, etc. and there is a need to get different modules executed depending upon the several roles of the person who wants access, different parameters can be passed accordingly to the middlewares.
There are sometimes middlewares that start functioning after the response is sent by the user to the request that comes. The terminate method is the actual method which is used by Laravel for the same. After the response is sent to the browser, the terminate method activates the terminable middlewares automatically.
The following example helps to understand it better:
Code:
<? Php
Namespace Illuminate\Session\Middleware;
Use Closure;
Class SessionBegin
{
Public function handle ($request, Closure $next)
{
Return $next ($request);
}
Public function terminate ($request, $response)
{
// tasks assigned within terminate method
}
}
Example to Implement Laravel Middleware
Let us look at how to generate a Laravel Middleware with the help of Artisan command.
Example #1
In the command, the terminal runs this command.
Code:
php artisan make:middleware Admin
Example #2
A middleware class will be generated with this command which will look like this
Code:
NamespaceApp\Http\Middleware;
UseClosure;
ClassAdmin
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
Publicfunctionhandle ($request, Closure $next)
{
Return $next ($request);
}
}
This will be available in the folder app/Http/Middleware.
Example #3
Register the middleware either as a Global middleware or as a Route Middleware depending upon the need to app/Http/Kernel.php You can register the admin middleware as mentioned below in the coding
Code:
@var array
*/
Protected $routeMiddleware = [
'Auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic'=> \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'Bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
'Cache. Headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
'Can' => \Illuminate\Auth\Middleware\Authorize::class,
'Guest'=> \App\Http\Middleware\RedirectIfAuthenticated::class,
'Password. Confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
'Signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
'Throttle'=> \Illuminate\Routing\Middleware\ThrottleRequests::class,
'Verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
'Admin' => \App\Http\Middleware\Admin::class,
];
Example #4
Updating the middleware is another important task. It is important that in this case no one other than the administrator gets access so it needs to be updated to be protected.
The handle () method helps us in actualizing this task. This is what you need to add inside the handle request:
Code:
Publicfunctionhandle ($request, Closure $next)
{
If (auth () ->user () ->is_admin == 1) {
Return $next ($request);
}
Returnredirect ('home') ->with ('error’, ‘You are not authorized to access admin pages.');
}
The unauthorized person will hereby be sent back to the home page as directed by the user in the coding above.
Conclusion
In conclusion we can say that Laravel middleware is an important feature provided by Laravel for the users who can use it to handle the exchange of information in the process of requests and responses that the application needs to take command over. It is a security feature that gives limited access if any random person tries to seek information or data from the application.
Recommended Articles
We hope that this EDUCBA information on “Laravel Middleware” was beneficial to you. You can view EDUCBA’s recommended articles for more information.