Middleware in Laravel provides a powerful way to filter HTTP requests entering your application. Whether you’re verifying a user’s role, logging activity, or rate-limiting traffic, middleware acts like a gatekeeper between the request and your application’s logic.

In this tutorial, we’ll walk through building a custom middleware from scratch. We’ll build a middleware that restricts access to routes unless a specific query parameter is present, for example, ?access=secret.

📦 Step 1: Create the Middleware

Run the Artisan command:

php artisan make:middleware CheckAccessKey

This creates a file at:
app/Http/Middleware/CheckAccessKey.php


📝 Step 2: Write Middleware Logic

Open CheckAccessKey.php and modify it like this:

<?php

namespace App\Http\Middleware;

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

class CheckAccessKey
{
    public function handle(Request $request, Closure $next): Response
    {
        if ($request->query('access') !== 'secret') {
            return response()->json([
                'message' => 'Access denied. Valid access key not provided.'
            ], 403);
        }

        return $next($request);
    }
}

💡 This middleware checks for a query parameter ?access=secret and blocks access otherwise.

⚙️ Step 3: Register the Middleware

Open app/Http/Kernel.php and register your middleware:

protected $routeMiddleware = [
    // ...
    'check.access' => \App\Http\Middleware\CheckAccessKey::class,
];

Now you can use it like any other route middleware.


🚀 Step 4: Apply to Routes

Use it in your web or API routes like this:

Route::get('/secret-data', function () {
    return response()->json(['data' => 'Top Secret Info']);
})->middleware('check.access');

🔍 Testing:

  • ✅ Accessing /secret-data?access=secret will return the data.
  • ❌ Accessing /secret-data without the query will return a 403 response.

🧠 Bonus: Making It Dynamic

Want the access key to come from .env?

if ($request->query('access') !== env('ACCESS_KEY')) {
    // deny access
}

Then define it in your .env:

ACCESS_KEY=mycustomsecret

🏁 Conclusion

Custom middleware is one of the most powerful and elegant tools in Laravel. Whether you’re building security checks, logging, or modifying requests on the fly, it’s your go-to solution for request filtering.

Similar Posts