How to create Middleware Laravel

Create custom Laravel middleware w/ example: learn how to check user roles & restrict access to routes & resources.

Creating Middleware in Laravel

In order to create a middleware in Laravel, you first need to open the app/Http/Kernel.php file. The $routeMiddleware property of the $kernel class contains an array of all the middleware that are registered with your application. To register a new middleware, you would simply add it to the array.


protected $routeMiddleware = [
  'auth' => AppHttpMiddlewareAuthenticate::class,
  'throttle' => IlluminateRoutingMiddlewareThrottleRequests::class,
  'newmiddleware' => AppHttpMiddlewareNewMiddleware::class,
];

The $routeMiddleware array contains a key-value pair, where the key is the name of the middleware and the value is the fully qualified class name of the middleware. For example, in the code above, the newmiddleware middleware is associated with the AppHttpMiddlewareNewMiddleware class.

Once the middleware has been registered, you can assign it to routes. To do this, you can use the middleware method on the Route facade. For example, to assign the newmiddleware middleware to a route, you would use the following code:


Route::get('/', function () {
  //
})->middleware('newmiddleware');

You can assign multiple middleware to a route by passing an array of middleware to the middleware method. For example:


Route::get('/', function () {
  //
})->middleware(['auth', 'throttle']);

To create an actual middleware class, you need to use the make:middleware Artisan command. For example, to create a middleware called NewMiddleware, you would run the following command:


php artisan make:middleware NewMiddleware

This command will create a new class called NewMiddleware in the app/Http/Middleware directory. The class will contain two methods: handle and terminate. The handle method will be called when the middleware is executed, and the terminate method will be called after the middleware has been executed.

The handle method receives two parameters: $request and $next. The $request parameter is an instance of the Request class, and the $next parameter is a Closure that you must call in order to execute the next middleware in the chain. For example:


public function handle($request, Closure $next)
{
  // Perform action

  return $next($request);
}

The middleware that you have created can now be used in your application.

Answers (0)