As a web developer, I love exploring tools that make my projects secure and efficient. Laravel 12, a powerful PHP framework, offers middleware—a fantastic feature for protecting routes.
Middleware acts like a gatekeeper, ensuring only authorized users access specific parts of your application. Whether you're safeguarding an admin dashboard or restricting API endpoints, middleware simplifies the process.
In this guide, I’ll walk you through using middleware for route protection in Laravel 12 with easy steps and code examples.
Middleware in Laravel 12 is a powerful tool for filtering HTTP requests, ensuring only authorized users access protected routes. Below, I’ll break down the process of creating and applying middleware for route protection, complete with code snippets to make it beginner-friendly.
Middleware acts as a bridge between an HTTP request and your application’s response. It checks conditions—like user authentication or roles—before allowing access to a route.
For example, Laravel’s auth
middleware ensures only logged-in users can access a route, redirecting others to the login page.
In Laravel 12, middleware configuration is streamlined in the bootstrap/app.php
file, making it easier to manage.
To get started, create a new Laravel 12 project using Composer. Open your terminal and run:
composer create-project laravel/laravel laravel-middleware-example
cd laravel-middleware-example
Ensure your database is configured in the .env
file. Then, run migrations to set up the default user authentication tables:
php artisan migrate
This sets up the foundation for testing middleware with authentication.
Laravel 12 allows you to create custom middleware using the Artisan command. Let’s create a middleware to check if a user is an admin. Run:
php artisan make:middleware CheckAdmin
This generates a CheckAdmin.php
file in the app/Http/Middleware
directory. Open it and modify the handle
method to check if the authenticated user has an is_admin
role:
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
class CheckAdmin
{
public function handle(Request $request, Closure $next): Response
{
if (auth()->check() && auth()->user()->is_admin) {
return $next($request);
}
return redirect('/home')->with('error', 'You are not authorized to access this page.');
}
}
This middleware checks if the user is logged in and has an is_admin
attribute set to true. If not, it redirects them to the home page with an error message.
In Laravel 12, middleware is registered in the bootstrap/app.php
file. Open it and add your middleware as an alias for easy route assignment:
use App\Http\Middleware\CheckAdmin;
return Application::configure(basePath: dirname(__DIR__))
->withRouting(
web: __DIR__.'/../routes/web.php',
commands: __DIR__.'/../routes/console.php',
health: '/up',
)
->withMiddleware(function (Middleware $middleware) {
$middleware->alias([
'admin' => CheckAdmin::class,
]);
})
->withExceptions(function (Exceptions $exceptions) {
//
})->create();
The admin
alias allows you to apply the CheckAdmin
middleware to routes using a simple name.
Now, let’s protect specific routes with the admin
middleware. Open routes/web.php
and define a protected route:
use Illuminate\Support\Facades\Route;
Route::get('/admin/dashboard', function () {
return "Welcome to the Admin Dashboard!";
})->middleware('admin');
This route is only accessible to authenticated users with the is_admin
attribute. You can also apply middleware to a group of routes:
Route::middleware(['admin'])->group(function () {
Route::get('/admin/users', function () {
return "Manage Users";
});
Route::get('/admin/settings', function () {
return "Admin Settings";
});
});
This groups multiple admin routes under the admin
middleware, keeping your code clean and DRY.
To test the middleware, ensure your application has authentication set up. Laravel 12 includes built-in authentication scaffolding. Install it using:
composer require laravel/ui
php artisan ui bootstrap --auth
npm install && npm run dev
Update your User
model to include an is_admin
column. Modify the migration file in database/migrations
to add:
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->boolean('is_admin')->default(false);
$table->timestamps();
});
Run the migration again:
php artisan migrate:fresh
Create a test user with admin privileges in your database or via a seeder:
use App\Models\User;
User::create([
'name' => 'Admin User',
'email' => '[email protected]',
'password' => bcrypt('password'),
'is_admin' => true,
]);
Start your Laravel server:
php artisan serve
/admin/dashboard
. You’ll be redirected to /home
with an error message.[email protected]
). You should see the “Welcome to the Admin Dashboard!” message.This confirms your middleware is working correctly.
Middleware can accept parameters for more flexibility. Let’s create a middleware that checks for specific user roles. Run:
php artisan make:middleware EnsureUserHasRole
Update app/Http/Middleware/EnsureUserHasRole.php
:
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
class EnsureUserHasRole
{
public function handle(Request $request, Closure $next, string $role): Response
{
if (auth()->check() && auth()->user()->role === $role) {
return $next($request);
}
return redirect('/home')->with('error', 'Unauthorized access.');
}
}
Register it in bootstrap/app.php
:
$middleware->alias([
'role' => EnsureUserHasRole::class,
]);
Apply it to a route:
Route::get('/editor/posts', function () {
return "Editor Dashboard";
})->middleware('role:editor');
This middleware ensures only users with the editor
role can access the route.
You can also apply middleware within controllers for more granular control. Create a controller:
php artisan make:controller DashboardController
Update app/Http/Controllers/DashboardController.php
:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class DashboardController extends Controller
{
public function __construct()
{
$this->middleware('admin')->only('index');
}
public function index()
{
return "Admin Dashboard via Controller";
}
}
Add a route in routes/web.php
:
Route::get('/dashboard', [DashboardController::class, 'index']);
The admin
middleware protects the index
method, ensuring only admins can access it.
If you encounter issues, ensure:
use Illuminate\Routing\Controller as BaseController;
).bootstrap/app.php
.For performance, avoid heavy logic in middleware. Use caching or database optimization for role checks in large applications.
Using middleware for route protection in Laravel 12 is a game-changer for securing web applications. From authentication to role-based access, middleware provides a clean, reusable way to filter HTTP requests. By following this guide, you’ve learned how to create, register, and apply middleware to routes and controllers. Experiment with custom middleware to tailor your app’s security to your needs. Laravel 12’s streamlined configuration makes it easier than ever to build secure, scalable applications. Start implementing middleware today and take your Laravel projects to the next level!
1. What is middleware in Laravel 12?
Middleware is a filtering mechanism that processes HTTP requests before they reach your application’s routes or controllers. It handles tasks like authentication, role checks, and logging.
2. How do I create a custom middleware in Laravel 12?
Use the Artisan command php artisan make:middleware MiddlewareName
to generate a middleware class in app/Http/Middleware
. Define your logic in the handle
method.
3. Where is middleware registered in Laravel 12?
Middleware is registered in the bootstrap/app.php
file using the withMiddleware
method, where you can define aliases or global middleware.
4. Can middleware accept parameters in Laravel 12?
Yes, middleware can accept parameters. Define them in the handle
method and pass them when applying the middleware, e.g., middleware('role:editor')
.
5. How do I apply middleware to a group of routes?
Use Route::middleware(['middlewareName'])->group(function () { ... })
in routes/web.php
to apply middleware to multiple routes efficiently.
6. Why is my middleware not working?
Ensure the middleware is registered in bootstrap/app.php
, the controller extends the base controller, and authentication is set up correctly. Check for typos in route definitions.
You might also like: