Laravel - Middleware: Your Gateway to Request Handling

Hello there, future Laravel developers! Today, we're going to dive into the fascinating world of Laravel Middleware. Think of middleware as a helpful security guard for your application - it checks and processes requests before they reach your main application logic. Let's embark on this exciting journey together!

Laravel - Middleware

What is Middleware?

Before we jump into the code, let's understand what middleware is. Imagine you're throwing a party (your application), and you have a bouncer (middleware) at the door. This bouncer can:

  1. Check if people are on the guest list (authentication)
  2. Make sure they're dressed appropriately (validation)
  3. Give them a wristband (add information to the request)
  4. Or even turn them away (terminate the request)

That's essentially what middleware does for your Laravel application!

Registering Middleware

Now, let's see how we can create and register our own middleware.

Creating Middleware

First, we'll create a simple middleware that checks if a user is over 18:

<?php

namespace App\Http\Middleware;

use Closure;

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

        return $next($request);
    }
}

In this example, our CheckAge middleware checks if the age parameter in the request is over 18. If not, it redirects to the home page. Otherwise, it passes the request to the next middleware or to the main application.

Registering Global Middleware

To use this middleware globally (for all routes), we need to register it in the app/Http/Kernel.php file:

protected $middleware = [
    // ...
    \App\Http\Middleware\CheckAge::class,
];

Registering Route Middleware

If you want to use the middleware only for specific routes, you can register it as a route middleware:

protected $routeMiddleware = [
    // ...
    'checkage' => \App\Http\Middleware\CheckAge::class,
];

Then, you can use it in your routes like this:

Route::get('adult-only', function () {
    //
})->middleware('checkage');

Middleware Parameters

Sometimes, we want our middleware to be more flexible. That's where middleware parameters come in handy!

Let's modify our CheckAge middleware to accept a minimum age parameter:

<?php

namespace App\Http\Middleware;

use Closure;

class CheckAge
{
    public function handle($request, Closure $next, $minAge)
    {
        if ($request->age <= $minAge) {
            return redirect('home');
        }

        return $next($request);
    }
}

Now, we can use this middleware with different age limits:

Route::get('adult-only', function () {
    //
})->middleware('checkage:18');

Route::get('senior-only', function () {
    //
})->middleware('checkage:65');

Isn't that neat? We've made our middleware reusable for different scenarios!

Terminable Middleware

Sometimes, we want our middleware to do something after the response has been sent to the browser. That's where terminable middleware comes in!

Let's create a middleware that logs the response time:

<?php

namespace App\Http\Middleware;

use Closure;

class LogResponseTime
{
    public function handle($request, Closure $next)
    {
        $request->start_time = microtime(true);

        return $next($request);
    }

    public function terminate($request, $response)
    {
        $duration = microtime(true) - $request->start_time;
        \Log::info('Response time: ' . $duration . ' seconds');
    }
}

This middleware adds a start_time to the request, then logs the total response time after the response has been sent.

To use terminable middleware, make sure it's registered in your app/Http/Kernel.php file:

protected $middleware = [
    // ...
    \App\Http\Middleware\LogResponseTime::class,
];

Middleware Methods

Here's a table of the main methods you'll use when working with middleware:

Method Description
handle() The main middleware logic. Processes the request and optionally passes it to the next middleware.
terminate() Runs after the response has been sent to the browser. Used for cleanup or logging.

Conclusion

And there you have it, folks! We've journeyed through the land of Laravel Middleware, from creating and registering middleware to using parameters and terminable middleware. Remember, middleware is like the Swiss Army knife of request handling - it's versatile, powerful, and an essential tool in your Laravel toolkit.

As you continue your Laravel adventure, you'll find countless creative ways to use middleware. Maybe you'll create middleware to check for maintenance mode, log requests, or even transform request data. The possibilities are endless!

Keep coding, keep learning, and most importantly, have fun! Until next time, happy Laravel-ing!

Credits: Image by storyset