How to assign middleware to routes in Laravel

Updated: January 18, 2024 By: Guest Contributor Post a comment

Introduction

Middlewares in Laravel are a powerful feature that allows you to filter HTTP requests entering your application. This tutorial will guide you through the process of creating and assigning middleware to routes in your Laravel application. Whether for authentication, logging, CORS, or any other purpose, Laravel’s middleware is up to the task.

Understanding Middleware

In Laravel, middleware provides a convenient mechanism for inspecting and filtering HTTP requests. You can use middleware to perform tasks like verifying a user’s authentication, logging requests, handling CORS, etc., before the request is processed by the application or after the response is sent to the browser.

Creating Middleware

php artisan make:middleware CheckAge

This command creates a new middleware class within the app/Http/Middleware directory.

Defining Middleware Logic

Edit the newly created CheckAge.php.

public function handle($request, Closure $next) 
   if (age < 18) {     return redirect('home');   }   return $next($request); }

This example checks if the user’s age is less than 18, and if so, it redirects them to the home page.

Global Middleware

Register the middleware in the app/Http/Kernel.php by adding it to the $middleware array.

'middleware' => [     
Illuminate
ewMiddleware"];

Group Middleware

If you want certain middleware to be used for a group of routes, define it under the $middlewareGroups array in Kernel.php.

$middlewareGroups = [   'web' => [      
AppHttpMiddleware
ewMiddleware],   'api' => [      

ewMiddleware'     ],];

Route Middleware

To assign middleware to specific routes, first register it in your app/Http/Kernel.php file.

protected $routeMiddleware = [ 
   'age' => 
AppHttpMiddleware
ewMiddleware'];

Once registered, you can use the middleware method to assign middleware to routes in your routes/web.php or routes/api.php files.

Route::get('/profile', function () {    
       // Only called if age middleware allows   
 })->middleware('age');

This will only execute the closure for the /profile route if the age middleware allows it.

Parameterized Middleware

You can also pass parameters to your middleware:

Route::get('/post/{post}', function (AppModelsPost $post) {}
)->middleware('role:editor');

This route will only be accessible to users who have the ‘editor’ role.

Middleware Priority

Sometimes you need to specify the order of middleware execution. In your Kernel.php, you can modify the $middlewarePriority array to achieve this.

Closure-based Middleware

For quick, simple checks, you can define middleware directly in the route using Closure.

Route::get('admin/profile', function () {
    // Your logic here
})->middleware(function ($request, $next) { 
    // Your validation logic here
    return $next($request);
});

This checks the logged-in user directly in the route definition.

Testing Middleware

After setting up middleware, you should test to ensure it’s working correctly. Laravel provides facilities for functional testing of your HTTP routes.

$response = $this->get('/route');
$response->assertStatus(403);

If the middleware restricts access, the status check should verify the proper error code.

Conclusion

Correctly applying middleware in Laravel helps keep your application secure and efficient. This guide walked you through defining, registering, and applying middleware to your routes. Middleware can streamline your application logic and provide an extra layer of control over HTTP requests in your Laravel application.