📚 Full Topic Coverage: Middleware in Laravel
1. What is Middleware in Laravel?
- Middleware is a type of filtering mechanism in Laravel.
- It acts as a bridge between a request and a response.
- It filters HTTP requests entering your application.
Example: Laravel’s built-in auth middleware checks if the user is authenticated.
2. How Middleware Works in Laravel
- Each request in Laravel goes through the middleware stack before reaching the controller.
- After the controller processes the request, the response goes back through the middleware stack.
3. Types of Middleware in Laravel
a. Global Middleware
- Registered in
app/Http/Kernel.phpunder$middleware. - Runs on every HTTP request.
b. Route Middleware
- Registered in
$routeMiddlewareinapp/Http/Kernel.php. - Applied only to specific routes.
c. Middleware Groups
- Registered under
$middlewareGroupslikewebandapi.
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
// ...
],
'api' => [
'throttle:api',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
];4. Creating Custom Middleware
bashCopyEditphp artisan make:middleware CheckUserRole
Example: app/Http/Middleware/CheckUserRole.php
public function handle($request, Closure $next)
{
if ($request->user() && $request->user()->role != 'admin') {
return redirect('/');
}
return $next($request);
}5. Registering Middleware
- Open
app/Http/Kernel.php - Add to:
$middlewarefor global$routeMiddlewarefor routes
protected $routeMiddleware = [
'role' => \App\Http\Middleware\CheckUserRole::class,
];6. Applying Middleware to Routes
a. Single Middleware
Route::get('/admin', function () {
// Only accessible by admin
})->middleware('role');b. Multiple Middleware
Route::get('/dashboard', function () {
// ...
})->middleware(['auth', 'role']);7. Middleware Parameters
You can pass parameters to middleware like this:
Route::get('/report', function () {
// ...
})->middleware('role:admin');Inside Middleware:
public function handle($request, Closure $next, $role)
{
if (! $request->user() || $request->user()->role !== $role) {
abort(403);
}
return $next($request);
}8. Terminable Middleware
- Used when you want to perform some task after the response is sent.
- Implement
terminate()method in the middleware.
public function terminate($request, $response)
{
Log::info('Request finished');
}Don’t forget to register it in the global middleware array in Kernel.php.
9. Middleware in API Authentication
- Use middleware like
auth:sanctumorauth:api. - Protect your API routes:
Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
return $request->user();
});10. Middleware Best Practices
- Keep middleware small and focused.
- Avoid business logic in middleware.
- Reuse middleware using groups or route aliasing.
- Use middleware for cross-cutting concerns (auth, logging, CORS, etc.)
Can middleware modify the request or response in Laravel?
Yes. Middleware can modify both the request (before it reaches the controller) and the response (after it leaves the controller).
$request->merge([‘new_key’ => ‘value’]);
$response = $next($request);
$response->header(‘X-Custom-Header’, ‘Value’);
return $response;
$request->merge([‘new_key’ => ‘value’]);
$response = $next($request);
$response->header(‘X-Custom-Header’, ‘Value’);
return $response;
What happens if middleware doesn’t return $next($request)?
The request won’t proceed to the next middleware or controller. This is typically used to short-circuit the request with redirects or error responses.
Can middleware be applied to controller methods only?
Yes. You can use the
public function __construct()
{
$this->middleware(‘auth’)->only([‘edit’, ‘update’]);
}
middleware method in the controller’s constructor.public function __construct()
{
$this->middleware(‘auth’)->only([‘edit’, ‘update’]);
}
How to exclude middleware from specific routes in a controller?
Use the
$this->middleware(‘auth’)->except([‘index’, ‘show’]);
except method in the controller constructor:$this->middleware(‘auth’)->except([‘index’, ‘show’]);
How to run middleware conditionally based on a request?
You can write logic inside the middleware to check the request type, user role, or URI and conditionally proceed.
if ($request->is(‘admin/*’)) {
// custom logic
}
if ($request->is(‘admin/*’)) {
// custom logic
}
Does middleware affect performance in Laravel?
Yes, slightly. Each middleware adds to the request lifecycle. Minimize heavy operations and prefer grouping where possible.
Can middleware be used for localization or language switching?
Yes. You can write a middleware that sets the application locale based on user preference or request headers.
App::setLocale($request->header(‘Accept-Language’));
App::setLocale($request->header(‘Accept-Language’));
How to test middleware in Laravel?
You can write middleware tests using Laravel’s HTTP testing layer.
$this->get(‘/admin’)->assertRedirect(‘/login’);
OR
$response = (new YourMiddleware)->handle($request, fn($req) => response(‘OK’));
$this->get(‘/admin’)->assertRedirect(‘/login’);
OR
$response = (new YourMiddleware)->handle($request, fn($req) => response(‘OK’));
Can middleware be reused in multiple Laravel projects?
Yes. You can extract it into a custom Laravel package or copy it across projects.
What are some examples of third-party middleware?
CORS handling:
JWT Auth: Middleware from
Role-based access: Middleware in
barryvdh/laravel-corsJWT Auth: Middleware from
tymon/jwt-authRole-based access: Middleware in
spatie/laravel-permissionCan middleware be skipped in Laravel?
You can’t “skip” middleware explicitly once applied, but you can use conditionals in your code or structure routes without middleware where needed.
How do I log all requests using middleware?
Create a global or route middleware that logs request data.
Log::info(‘Request’, [‘url’ => $request->fullUrl()]);
Log::info(‘Request’, [‘url’ => $request->fullUrl()]);
How does middleware differ in web and API routes?
web middleware includes session, CSRF protection, etc.api middleware is stateless, often uses token-based auth and throttling.Should middleware contain business logic?
No. Middleware should only handle cross-cutting concerns like authentication, logging, etc. Business logic belongs in services or controllers.
📝 Conclusion
Middleware in Laravel is a powerful mechanism to filter and manage HTTP requests. It supports both global and route-specific logic, allows parameter passing, and enables custom security or logging features. With best practices in place, middleware ensures your application is modular, secure, and maintainable.
