Just imagine you’re hosting a fabulous party. And you just want to be sure that the right people only get in the event by checking IDs or making sure everyone follows the same dress code. Originally that’s what Laravel middleware does for your web applications. It works as a friendly bouncer, filtering and managing all of the incoming requests before they reach your core application logic.
If you’ve been experimenting with PHP, you understand the importance of handling data and requests efficiently. Laravel’s middleware takes this to the next-level approach, where it provides a tidy and organized way to manage these interactions.
What Exactly is Laravel Middleware?
If you think of middleware as a series of checkpoints that every HTTP request must go through, it’s like a chain of functions that can be executed before your route and controller logic. Each of the checkpoints can carry out particular specific tasks, such as:
- Authentication: It verify the user’s credential and ensures that they’re logged in.
- Authorization: It checks if a user has the emergent permission to access a resource or not.
- Logging: In this section, it records the request details for debugging or auditing.
- Input Validation: It ensures that the incoming data is in the correct format and meets the specific criteria.
- Request Modification: In this section, it acts for adding or changing request data, like setting default values or formatting input.
How Middleware Works in Laravel 12.x (The Simplified Breakdown)
- Incoming Request: At this point, the user sends a request to the application (for example ., visiting a webpage or submitting a form). And this is the first step.
- Middleware Chain: In this section, the request enters the middleware chain where Laravel uses to execute the middleware methodically in the order as they’re registered.
- Middleware Execution: Each one of the middleware in the chain gets a chance to inspect and modify as per the request.
- Handle Method: Inside each of the middleware, the handle method is somewhat where the magic occurs. This method contains your custom logic.
- $next($request): If the middleware allows the request to continue, it calls $next($request). This passes the request to the next middleware in the chain or, if it’s the last middleware, to your route and controller.
- Response: At this point your application processes the request and sends a response back to the user.
Where to Find and Configure Middleware (Laravel 12.x)
Now, while discussing a crucial point, it can be said that in Laravel 12.x, primarily you’ll find and configure middleware in the bootstrap/app.php file, which is very obvious. This is a change from older Laravel versions, where app/Http/Kernel.php was the primary location.
Creating Your Own Middleware (Step-by-Step)
Now, we create a simple middleware that checks if a user is an admin in a very few easy steps.
Generate the Middleware
- Open your terminal and navigate to your Laravel project directory.
- Run the command:
php artisan make:middleware AdminCheck
- This will create a new middleware file in the app/Http/Middleware
Write the Logic
- Open the app/Http/Middleware/AdminCheck.php
- Inside the handle method, add your logic:
<?php namespace App\Http\Middleware; use Closure; use Illuminate\Http\Request; use Symfony\Component\HttpFoundation\Response; class AdminCheck { public function handle(Request $request, Closure $next): Response { // Here we checking if the user is an admin (replace with your actual logic) $isAdmin = true; // For demonstration purposes if (!$isAdmin) { return response('Unauthorized', 403); // Return a 403 Forbidden response } return $next($request); // Allow the request to continue } }
* Remember to replace the `$isAdmin = true;` with your actual authentication and authorization logic.
Register the Middleware
-
- Open bootstrap/app.php
- Inside the withMiddleware closure, add the alias of your middleware.
<?php
use App\Http\Middleware\AdminCheck; use Illuminate\Foundation\Application; use Illuminate\Support\Facades\Route; return Application::configure(basePath: dirname(__DIR__)) ->withRouting( web: __DIR__.'/../routes/web.php', commands: __DIR__.'/../routes/console.php', health: '/up', )->withMiddleware(function ($middleware) { $middleware->alias('admin', AdminCheck::class); })->withExceptions(__DIR__.'/../app/Exceptions/Handler.php') ->withCore();
Read More Article About Laravel
Laravel Routing: Basic Routes, Parameters & Groups | TutorialDev
Laravel 12.x Configuration Guide (Simplified)
Understanding Laravel’s Directory Structure in Simple Terms With Easy Steps
Use the Middleware in Your Routes
Open your routes/web.php
Apply the middleware to a route:
Route::get('/admin/dashboard', function () { return 'Welcome to the admin dashboard!'; })->middleware('admin');
Why Middleware is Your Friend
- Code Organization: Middleware helps in keeping your controllers clean, tidy, and focused on their core responsibilities so it can act properly and wisely.
- Reusability: Middleware can be reused across multiple routes. which is very easy to access.
- Security: Middleware provides a centralized place to handle authentication and authorization to maintain further security. Because maintaining security is the most crucial part of it.
- Flexibility: Another feature is flexibility, so you can easily include or exclude middleware as the way your application grows. Flexibility is the ultimate thing while working in web applications.
In the conclusion, we can say that by understanding and using Laravel middleware, you’ll be able to build more sturdy, secure, invulnerable, impervious, and maintainable web applications, and there is no doubt about it. So, you should go ahead, experiment, and have fun building your own middleware!