Creating Custom Middleware
Custom middleware lets you add your own logic to the request pipeline - checking user roles, logging requests, enforcing HTTPS, setting locale, or adding response headers. Generate with php artisan make:middleware.
Custom Middleware Examples
// php artisan make:middleware EnsureUserIsAdmin
namespace App\Http\Middleware;
class EnsureUserIsAdmin
{
public function handle(Request $request, Closure $next)
{
if (!$request->user()?->isAdmin()) {
abort(403, 'Admin access required.');
}
return $next($request); // Pass to next middleware
}
}
// Logging middleware (before & after)
class LogRequestDuration
{
public function handle(Request $request, Closure $next)
{
$start = microtime(true);
$response = $next($request); // Execute controller
$duration = round((microtime(true) - $start) * 1000, 2);
Log::info("Request: {$request->method()} {$request->path()} took {$duration}ms");
return $response;
}
}
// Header middleware (modify response)
class AddSecurityHeaders
{
public function handle(Request $request, Closure $next)
{
$response = $next($request);
$response->headers->set('X-Frame-Options', 'DENY');
$response->headers->set('X-Content-Type-Options', 'nosniff');
return $response;
}
}Industry Best Practices
- Always write tests for this functionality - it's the most reliable way to catch regressions when you refactor or update packages
- Document your implementation decisions in code comments, especially when you deviate from Laravel conventions - future team members (including yourself) will thank you
- Follow the single responsibility principle: each class does one thing. If a method grows beyond 20 lines, consider extracting helper methods or moving logic to a service class
- Profile performance with Laravel Debugbar (composer require barryvdh/laravel-debugbar) during development - it shows query counts, memory usage, and timeline for every request
- Keep dependencies up to date: run composer audit regularly to check for security vulnerabilities in your package dependencies
Industry Best Practices
- Always write tests for this functionality - it's the most reliable way to catch regressions when you refactor or update packages
- Document your implementation decisions in code comments, especially when you deviate from Laravel conventions - future team members (including yourself) will thank you
- Follow the single responsibility principle: each class does one thing. If a method grows beyond 20 lines, consider extracting helper methods or moving logic to a service class
- Profile performance with Laravel Debugbar (composer require barryvdh/laravel-debugbar) during development - it shows query counts, memory usage, and timeline for every request
- Keep dependencies up to date: run composer audit regularly to check for security vulnerabilities in your package dependencies
Industry Best Practices
- Always write tests for this functionality - it's the most reliable way to catch regressions when you refactor or update packages
- Document your implementation decisions in code comments, especially when you deviate from Laravel conventions - future team members (including yourself) will thank you
- Follow the single responsibility principle: each class does one thing. If a method grows beyond 20 lines, consider extracting helper methods or moving logic to a service class
- Profile performance with Laravel Debugbar (composer require barryvdh/laravel-debugbar) during development - it shows query counts, memory usage, and timeline for every request
- Keep dependencies up to date: run composer audit regularly to check for security vulnerabilities in your package dependencies
Tip
Tip
Practice Creating Custom Middleware in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Middleware wraps requests in and responses out like an onion
Practice Task
Note
Practice Task - (1) Write a working example of Creating Custom Middleware from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with Creating Custom Middleware is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready laravel code.
Key Takeaways
- Custom middleware lets you add your own logic to the request pipeline - checking user roles, logging requests, enforcing HTTPS, setting locale, or adding response headers.
- Always write tests for this functionality - it's the most reliable way to catch regressions when you refactor or update packages
- Document your implementation decisions in code comments, especially when you deviate from Laravel conventions - future team members (including yourself) will thank you
- Follow the single responsibility principle: each class does one thing. If a method grows beyond 20 lines, consider extracting helper methods or moving logic to a service class