Laravel Middleware

Lesson 19 of 50 - Learn how middleware filters HTTP requests.

38%
1. What Is Middleware?

Middleware is a layer between an incoming HTTP request and your application's response. It can inspect a request, allow it to continue, or reject it before it reaches a controller or route.

Common uses of middleware include:

  • Checking whether a user is logged in.
  • Restricting access to admin pages.
  • Checking user permissions.
  • Filtering requests based on certain conditions.
  • Adding security-related request checks.

For example, authentication middleware can redirect a guest user to the login page instead of allowing access to a protected dashboard.

2. How Middleware Works

A simplified request flow looks like this:

User Request
     |
     v
Middleware
     |
     v
Route / Controller
     |
     v
Application Response
     |
     v
User Browser

Middleware can also inspect or modify the response after the route or controller has handled the request.

If a middleware condition fails, it can return a response or redirect instead of allowing the request to continue.

3. Create Custom Middleware

Use the Artisan command to create a middleware class.

php artisan make:middleware CheckAge

Laravel creates the middleware in the app/Http/Middleware directory in a standard application structure.

Open CheckAge.php and write:

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class CheckAge
{
    public function handle(Request $request, Closure $next): Response
    {
        if ($request->input('age', 0) < 18) {
            return response('You must be at least 18 years old.', 403);
        }

        return $next($request);
    }
}

The middleware checks the request's age input. If the age is below 18, it returns a 403 response. Otherwise, $next($request) passes the request to the next middleware or route.

This is a learning example. Real age verification should not rely only on a user-submitted value.

4. Register Middleware in Laravel

Middleware registration depends on your Laravel version.

Laravel 11 and newer standard applications:

Open bootstrap/app.php and register the middleware alias inside the existing withMiddleware configuration.

use App\Http\Middleware\CheckAge;
use Illuminate\Foundation\Configuration\Middleware;

->withMiddleware(function (Middleware $middleware): void {
    $middleware->alias([
        'check.age' => CheckAge::class,
    ]);
})

Add this configuration inside the existing Application::configure(...) chain; do not replace the entire file with this fragment.

Laravel 10 standard applications:

Register the alias in the $middlewareAliases property of app/Http/Kernel.php.

protected $middlewareAliases = [
    // Existing aliases...

    'check.age' => \App\Http\Middleware\CheckAge::class,
];

Follow the registration structure used by your installed Laravel version.

5. Apply Middleware to a Route

Once registered, you can apply the middleware alias to a route using the middleware() method.

use Illuminate\Support\Facades\Route;

Route::get('/restricted', function () {
    return 'You are allowed to access this page!';
})->middleware('check.age');

Open /restricted?age=20 to pass the example check. Open /restricted?age=15 to receive a 403 response.

The example reads age from the request input, including query parameters. It demonstrates middleware flow rather than secure age verification.

6. Apply Middleware to a Route Group

You can apply the same middleware to multiple routes by placing them inside a route group.

Route::middleware(['check.age'])->group(function () {

    Route::get('/course', function () {
        return 'Welcome to the course page!';
    });

    Route::get('/exam', function () {
        return 'Welcome to the exam page!';
    });

    Route::get('/certificate', function () {
        return 'Welcome to the certificate page!';
    });

});

All three routes use the check.age middleware.

Route groups are useful when several pages need the same authentication, authorization, or request checks.

7. Use Built-in Authentication Middleware

Laravel provides authentication middleware through the auth alias.

Route::get('/dashboard', function () {
    return view('dashboard');
})->middleware('auth');

This route requires an authenticated user. Your application must have authentication configured.

You can also protect a group of routes:

Route::middleware('auth')->group(function () {

    Route::get('/profile', function () {
        return 'User Profile';
    });

    Route::get('/settings', function () {
        return 'User Settings';
    });

});

Authentication confirms the user's identity. It does not automatically mean the user has permission to perform every action.

8. Global and Route Middleware

Middleware can be applied at different levels.

Type Purpose
Global middleware Runs for requests handled through the application's HTTP middleware pipeline.
Route middleware Runs only on routes or groups where it is applied.
Middleware groups Combine middleware for common purposes, such as web or API requests.

In modern Laravel applications, middleware configuration is commonly managed in bootstrap/app.php. Older application structures may use app/Http/Kernel.php.

Add middleware globally only when it genuinely needs to run for the relevant application requests.

9. Practical Assignment

Create a custom middleware system with the following requirements:

  1. Create middleware named CheckAge.
  2. Return a 403 response when the example age is below 18.
  3. Allow the request to continue when the age is 18 or above.
  4. Register the middleware using the correct method for your Laravel version.
  5. Apply it to a course route.
  6. Apply it to a group containing three routes.
  7. Protect a dashboard route using the built-in auth middleware.

Test each route and observe when the request reaches the route and when middleware returns a response early.

Quick Quiz

1. What is the main purpose of middleware?




2. Which method passes a request to the next middleware or route?




3. Which middleware alias commonly requires authentication?