DEV Community

Cover image for Defining middleware into Laravel Application.
Osman Forhad
Osman Forhad

Posted on

Defining middleware into Laravel Application.

We all know middleware is most important Method to developing Laravel Application. Here I will Discussed About Laravel middleware.

So, what is middleware.?
In Laravel, middleware is a type of filtering mechanism. Middleware act’s as a bridge between a request and response.
More briefly: In Laravel middleware provide a convenient mechanism for filtering HTTP Requests entering web application.
For example, Laravel includes a middleware that verifies that user of Developer Application is authenticated. If the user isn’t Authenticated, the middleware will redirect the user to the login screen or Developer Defined page.
However, if the user is authenticated, the middleware will allow the request to processed further into the Application.There are several middleware included in the Laravel framework, including middleware for Authentication and CSRF protection. All of this middleware are located in the
app/Http/middleware directory
So, what is CSRF.?
CSRF(Cross Site Request Forgery) use to protect Application from cross-site Request of Attackers.
Laravel automatically generate a CSRF token for each active user Session manage by the Application.
This token can verify that the request is making in the application is generated by authenticated user or not.
Defining middleware.?
To create a new middleware, I use the make: middleware artisan command.
php artisan make: middleware nameofthefile(as you like)
in my case I give the file name is Administrator
This command will place a new file/class which name is Administrator within Laravel Application app/Http/middleware directory.
In this class I will write code for only allow to access the route of the Supplied age is less than 18, otherwise, we will redirect the user back into the home url.
The middleware class like below:
<?php
namespace App\Http\middleware;
use Closure;
class Administrator{
/**
*
*@param \Illuminate\Http\Request $request
*@param \Closure $next
*return mixed
*/
public function handle ($request, Closure $next) {
if($request->age<=18) {
return redirect(‘home’);
}//end of if condition
return $next($request);
}//end of the function
}//end of the class
Now the Result is, if the given age is less than or equal to 18, The middleware will return an http redirect to the client; otherwise the request will be passed further into the application.
To pass the request deeper into the application.
(allowing the middleware to “pass”), call the $next callback with the $request
.
that's it.
.
Happy Coding.
osman forhad
Mobile & Web Application Developer💻

Discussion (0)