Kritim Yantra
Mar 05, 2025
Welcome to this beginner-friendly guide on Laravel 12 middleware! If you're new to Laravel or web development, don’t worry—we’ll walk through everything step-by-step.
In this blog post, we’ll explore what middleware is, how it works in Laravel 12, and how to register it in the bootstrap/app.php
file (a change from earlier versions where it was done in app/Http/Kernel.php
).
By the end, you’ll know how to create and use middleware to enhance your Laravel applications. Let’s dive in!
Imagine middleware as a series of checkpoints that an HTTP request must pass through before reaching your application—or before the response is sent back to the user. It’s like a filter or gatekeeper that can inspect, modify, or even block requests based on certain conditions.
For example:
In Laravel, middleware is a powerful tool that helps you manage these tasks efficiently, keeping your code organized and reusable.
Middleware is essential because it helps you:
Simply put, middleware helps build secure and organized applications without cluttering your routes or controllers.
Let’s start by creating our own middleware. Laravel’s Artisan command makes this easy.
Open your terminal and run:
php artisan make:middleware CheckAdmin
This generates a new file called CheckAdmin.php
in the app/Http/Middleware
directory. Open it, and you’ll see something like:
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
class CheckAdmin
{
public function handle(Request $request, Closure $next)
{
return $next($request);
}
}
The handle
method is where your middleware logic lives. Let’s modify it to check if a user is an admin:
public function handle(Request $request, Closure $next)
{
if (!auth()->check() || !auth()->user()->is_admin) {
abort(403, 'Unauthorized - Admins only!');
}
return $next($request);
}
Here’s what this does:
auth()->check()
: Ensures the user is logged in.auth()->user()->is_admin
: Checks if the authenticated user has the is_admin
attribute set to true.abort(403, 'Unauthorized - Admins only!')
: Stops the request with a 403 Forbidden error if the check fails.$next($request)
: Passes the request to the next middleware or controller if the user is an admin.
In Laravel 12, middleware registration now occurs in the bootstrap/app.php
file instead of app/Http/Kernel.php
.
This centralizes configuration and streamlines the setup process.
Here’s an example of the basic structure in bootstrap/app.php
:
<?php
use Illuminate\Foundation\Application;
return Application::configure(basePath: dirname(__DIR__))
->withRouting(
web: __DIR__.'/../routes/web.php',
commands: __DIR__.'/../routes/console.php'
)
->withMiddleware(function ($middleware) {
//
})
->create();
Let’s explore the three ways to register middleware:
Global middleware runs on every HTTP request. To register your CheckAdmin
middleware globally (although for admin checks you might typically use route middleware), add it like this:
->withMiddleware(function ($middleware) {
$middleware->append(\App\Http\Middleware\CheckAdmin::class);
})
Use append
to add it to the end of the global middleware stack, or prepend
to add it at the beginning.
Middleware groups bundle multiple middleware together and apply them to specific route types. For example, create an admin group:
->withMiddleware(function ($middleware) {
$middleware->group('admin', [
\Illuminate\Session\Middleware\StartSession::class,
\App\Http\Middleware\CheckAdmin::class,
]);
})
This defines an admin group that includes session management and your CheckAdmin
middleware.
Route middleware lets you apply middleware to specific routes by giving them an alias. Register the alias like this:
->withMiddleware(function ($middleware) {
$middleware->alias([
'admin' => \App\Http\Middleware\CheckAdmin::class,
]);
})
Now you can use the alias admin
in your routes.
With your middleware registered, you can apply it in different ways:
use Illuminate\Support\Facades\Route;
Route::get('/admin/dashboard', function () {
return "Welcome to the Admin Dashboard!";
})->middleware('admin');
The admin
alias applies the CheckAdmin
middleware to the route. Only logged-in admins can access the dashboard.
Route::middleware('admin')->group(function () {
Route::get('/admin/dashboard', function () {
return "Welcome to the Admin Dashboard!";
});
Route::get('/admin/settings', function () {
return "Admin Settings Page";
});
});
All routes in the group inherit the middleware defined in the admin group.
class ProfileController extends Controller
{
public function __construct()
{
$this->middleware('admin');
}
public function show()
{
return "Profile page";
}
}
This applies the admin
middleware to all actions in the controller.
To make your middleware more flexible, you can pass parameters. For instance, update your CheckAdmin
middleware to accept a minimum age parameter:
public function handle(Request $request, Closure $next, $minAge)
{
if ($request->age < $minAge) {
return redirect('home');
}
return $next($request);
}
Then, apply it to a route with the parameter:
Route::get('/profile', function () {
return "Profile page";
})->middleware('check.age:21');
Here, the middleware checks that the user’s age is at least 21.
Let’s build a practical example: a middleware that ensures a user is logged in before accessing certain pages.
Run the following Artisan command:
php artisan make:middleware EnsureUserIsAuthenticated
Open app/Http/Middleware/EnsureUserIsAuthenticated.php
and update the handle
method:
public function handle(Request $request, Closure $next)
{
if (!auth()->check()) { // Check if user is logged in
return redirect('login'); // Redirect if not authenticated
}
return $next($request);
}
In bootstrap/app.php
, add it to the route middleware aliases:
->withMiddleware(function ($middleware) {
$middleware->alias([
'auth.user' => \App\Http\Middleware\EnsureUserIsAuthenticated::class,
]);
})
Protect a route by applying the middleware:
Route::get('/dashboard', function () {
return "Welcome to your dashboard!";
})->middleware('auth.user');
Now, only authenticated users can access the dashboard; others will be redirected to the login page.
Middleware in Laravel 12 is a powerful way to manage HTTP requests and responses, and moving its registration to bootstrap/app.php
has made configuration cleaner and more intuitive.
In this guide, we covered:
withMiddleware
method in bootstrap/app.php
.The best way to master middleware is to practice! Try creating your own middleware—such as one that logs requests or checks user roles—and apply it to your project. For more insights, check out the official Laravel documentation.
Happy coding, and welcome to the world of Laravel middleware!
No comments yet. Be the first to comment!
Please log in to post a comment:
Continue with Google