Laravel 12 Middleware Guide: Enhance Your Web Application with Real-World Examples & Best Practices

Introduction
Middleware is one of the most powerful features in Laravel 12, allowing you to filter HTTP requests entering your application. Whether you want to authenticate users, log requests, optimize performance, or apply custom logic, Laravel middleware provides a flexible and efficient way to handle these tasks.
In this blog post, we’ll explore different ways to use middleware in Laravel to enhance your web application. We will cover applying middleware in the routes/web.php
file, using middleware within controllers, and discuss real-time use cases such as rate limiting, localization, and API authentication. By the end of this guide, you’ll have a solid understanding of how to leverage Laravel middleware to improve your application’s security and functionality.
Option 1: Global Middleware
If you want a middleware to run during every HTTP request to your application, you may append it to the global middleware stack in your application's bootstrap/app.php
file:
use App\Http\Middleware\EnsureTokenIsValid;
->withMiddleware(function (Middleware $middleware) {
$middleware->append(EnsureTokenIsValid::class);
})
The $middleware object provided to the withMiddleware closure is an instance of Illuminate\Foundation\Configuration\Middleware
and is responsible for managing the middleware assigned to your application's routes. The append method adds the middleware to the end of the list of global middleware. If you would like to add a middleware to the beginning of the list, you should use the prepend method.
Option 2: Applying Middleware in the routes/web.php File
The routes/web.php file is where you define your application's web routes. Laravel allows you to apply middleware to these routes in two ways: individually per route or to a group of routes.
Individual Middleware per Route
You can apply middleware to a single route by chaining the middleware method to the route definition. This is useful when you want to apply specific middleware to a particular route.
Route::get('/dashboard', function () { // Your logic here })->middleware('auth');
In this example, the auth middleware ensures that only authenticated users can access the /dashboard route. You can also apply multiple middleware by passing an array:
Route::get('/profile', function () { // Your logic here })->middleware(['auth', 'verified']);
Middleware Groups
If you have a set of routes that share the same middleware, you can group them together using the Route::group method. This approach keeps your code DRY (Don’t Repeat Yourself) and makes it easier to manage middleware for multiple routes.
Route::middleware(['auth', 'verified'])->group(function () { Route::get('/dashboard', function () { // Your logic here }); Route::get('/profile', function () { // Your logic here }); });
In this example, both the /dashboard and /profile routes are protected by the auth and verified middleware.
Option 3 : Applying Middleware in Controllers
While applying middleware in the routes/web.php file is common, you can also define middleware directly within your controllers. This approach is useful when you want to encapsulate middleware logic within the controller itself.
Using the
middleware
MethodLaravel allows you to define middleware directly in your controller using the middleware method. This method is typically used in the controller's constructor or as a static method.
Here’s an example of applying middleware in the constructor:
class DashboardController extends Controller { public function __construct() { $this->middleware('auth'); $this->middleware('verified')->only('show'); } public function index() { // Your logic here } public function show() { // Your logic here } }
In this example:
- The
auth
middleware is applied to all methods inDashboardController
. - The
verified
middleware is only applied to theshow
method.
If you encounter an error that the middleware function is not found in your controller, ensure your custom controller extends Laravel's base controller.
Here’s how you can update your App\Http\Controllers\Controller.php file to ensure it extends the correct base controller and inherits the middleware method:
Updated Controller.php File:
<?php namespace App\Http\Controllers; use Illuminate\Routing\Controller as BaseController; abstract class Controller extends BaseController { // }
- The
Using the middleware
Static Method
Alternatively, you can define middleware as a static method within your controller. This approach is less common but can be useful in certain scenarios.
class ProfileController extends Controller { public static function middleware(): array { return [ 'auth', 'verified' => ['only' => ['edit']], ]; } public function edit() { // Your logic here } public function update() { // Your logic here } }
In this example, the auth middleware is applied to all methods, while the verified middleware is only applied to the edit method.
Real-Time Use Cases for Middleware in Laravel
1. API Authentication Middleware
For applications with APIs, Laravel provides built-in middleware for authentication using API tokens or JWT.
Route::middleware('auth:sanctum')->get('/user', function (Request $request) { return $request->user(); });
2. Rate Limiting for API Protection
To prevent abuse, you can limit the number of requests a user can make within a given timeframe.
Route::middleware('throttle:60,1')->group(function () { Route::get('/data', function () { return response()->json(['message' => 'Success']); }); });
3. Logging Requests for Debugging
Middleware can be used to log requests for debugging purposes.
class LogRequests { public function handle($request, Closure $next) { \Log::info('Incoming request', ['url' => $request->url(), 'data' => $request->all()]); return $next($request); } }
4. Localization Middleware
Set the application’s language dynamically based on user preferences.
class SetLocale { public function handle($request, Closure $next) { app()->setLocale($request->header('Accept-Language', 'en')); return $next($request); } }
5. Custom Header Injection
Modify the response by injecting a custom header.
class AddCustomHeader { public function handle($request, Closure $next) { $response = $next($request); $response->headers->set('X-Developer', 'YourName'); return $response; } }
Conclusion
Middleware is a versatile tool in Laravel that allows you to handle a wide range of tasks, from authentication and security to request modification and API rate limiting. By applying middleware in the routes/web.php
file or within controllers, you can tailor your application’s behavior to meet your specific needs.
Key Takeaways:
- Use middleware for authentication, logging, rate limiting, localization, and more.
- Apply middleware globally, per route, or within controllers for flexibility.
- Implement real-time use cases to improve application security and performance.