Introduction to Laravel Middleware


Middleware in Laravel is like a gatekeeper. When a user sends a request to your application, it passes through layers before it reaches your route or controller. Each layer is a middleware that can approve, reject, or modify the request.
If you’re new to Laravel, middleware might sound complicated. But once you see it in action, it’ll make a lot more sense.
In this tutorial, you'll learn how to create a custom middleware that blocks outdated browsers from accessing a specific route. You’ll also learn how to register the middleware and apply it to routes. By the end, you’ll have a good grasp of the basics and enough confidence to create your own.
Let’s get started.
Step 1: Create a New Middleware
Laravel gives you an Artisan command to generate boilerplate code for new middleware. First, open your terminal and navigate to the root folder of your Laravel app. From there, run the following command:
php artisan make:middleware BlockOldBrowsers
This creates a new file called BlockOldBrowsers.php
in the app/Http/Middleware
directory. You’ll write your custom logic inside this file.
At this point, nothing will happen when you run your app. All you’ve done is generate a placeholder. In the next step, you’ll add the logic that makes it functional.
When you run the make:middleware
command, it generates a class with a handle()
method. This method will control what happens when a request hits your middleware.
Right now, your middleware doesn’t do anything special. That’s what we’ll change next.
Step 2: Add Logic to the Middleware
Open the file you just created: app/Http/Middleware/BlockOldBrowsers.php
. Replace the contents of the file with the code below.
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
class BlockOldBrowsers
{
public function handle(Request $request, Closure $next): Response
{
$userAgent = $request->header('User-Agent');
if (preg_match('/MSIE [1-9]|MSIE 10/', $userAgent)) {
return response('Your browser is not supported. Please update your browser.', 403);
}
return $next($request);
}
}
This middleware looks at the browser information in the request. If it sees Internet Explorer version 10 or lower, it blocks the request and returns a 403 Forbidden message.
If the browser is anything else — Chrome, Firefox, Safari, Edge — the request goes through.
Explaining the Step
The $request
object contains all the information about the incoming HTTP request. The User-Agent
header tells you what browser the user is using. We're using a regular expression (preg_match
) to look for signatures of outdated Internet Explorer browsers.
If the condition is true, the middleware returns an early response. That stops the request from going any further. If the condition is false, it calls $next($request)
to pass the request on to the next step — usually your route or controller.
This is the heart of what middleware does: it either lets the request continue or stops it based on some logic.
Step 3: Register the Middleware
Now that your middleware has logic, Laravel needs to know about it. Otherwise, it won’t ever run.
Open the bootstrap/app.php
file. This file is where Laravel bootstraps your entire application and configures global settings — including middleware.
Add the following line inside that function:
$middleware->alias([
'block.old.browsers' => \App\Http\Middleware\BlockOldBrowsers::class
]);
This gives your middleware a short name that you can reuse in your routes. You won’t need to type the full class name every time.
Laravel lets you assign aliases to your middleware to keep your code clean. Instead of referencing App\Http\Middleware\BlockOldBrowsers::class
in your routes, you can now just use 'block.old.browsers'
.
This makes your route definitions easier to read and maintain. It’s a small detail, but it helps keep your codebase organized as it grows.
Step 4: Use the Middleware in a Route
Now that everything is in place, you can use your middleware in a real route.
Open the routes/web.php
file. This is where you define your app’s web routes.
Add a new route like this:
Route::get('/dashboard', function () {
return 'Welcome to the dashboard!';
})->middleware('block.old.browsers');
This route will now use your custom middleware. If a user tries to visit /dashboard
with an outdated browser, they’ll get blocked with a 403 error.
Everyone else will see the dashboard message as expected.
You’ve now put your middleware to work. This is how middleware fits into Laravel's routing system — you attach it to any route you want to protect.
You can also assign middleware to groups of routes or to controller methods, but for now, applying it to one route is enough to understand the concept.
Step 5: Test the Middleware
To make sure everything works, you should simulate a request with an old browser.
You can do this with a tool like curl. In your terminal, run:
curl -H "User-Agent: Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)" http://your-app.test/dashboard
This simulates a request from Internet Explorer 10. If your middleware is working, you’ll see the message: Your browser is not supported.
Now try visiting the route in a modern browser like Chrome. You should see the regular dashboard message.
This kind of testing is useful because you don’t need to install an outdated browser just to verify your code. By customizing the User-Agent
header, you can simulate almost any client.
Your middleware logic is now fully tested and working as expected.
Recap
In this tutorial, you created a custom middleware from scratch. You started with a simple Artisan command to generate the class. Then, you added logic that checks the browser’s User-Agent
and blocks requests from old browsers.
You registered the middleware by giving it an alias inside the bootstrap/app.php
file. Finally, you applied the middleware to a route and tested it to make sure it worked.
By following this step-by-step process, you've learned the essential parts of creating and using middleware in Laravel.
What’s Next?
Now that you understand the basics, you can start creating more useful middleware. Here are a few ideas to explore next:
Build a middleware that checks the user's country using their IP and blocks certain regions.
Add middleware that logs requests to a custom file for auditing.
Create middleware that checks if a user has completed onboarding before accessing the dashboard.
You can also learn about middleware groups, middleware parameters, and terminable middleware — which lets you run code after a response is sent.
Middleware is a foundational feature in Laravel, and now you have the skills to use it confidently.
Keep experimenting, and happy coding!
Subscribe to my newsletter
Read articles from Darrin Deal directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
