How to Create Custom Middleware in Laravel
Middleware acts as a bridge between a request and the application. It can intercept incoming requests, process them, and even terminate them before they reach your application logic.
Generate Middleware :
To start you’ll need to create a new middleware class. Open your terminal and run the following command
php artisan make:middleware CustomMiddleware
This command creates a new file in the app/Http/Middleware
directory.
Implement Middleware Logic:
Open the newly created middleware and add your custom logic.
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
class CustomMiddleware
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse) $next
* @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
*/
public function handle(Request $request, Closure $next)
{
//Check if the user is an admin
if (!auth()->user() || !auth()->user()->isAdmin()) {
return redirect('/home');
}
return $next($request);
}
}
We check if the authenticated user is an admin. If not they’re redirect to the home page.
Register Middleware:
After implementing the middleware logic, you need to register your middleware. Open the app/Http/Kernel.php
file. You can register it either as global middleware or route-specific middleware. For most use cases, you’ll want to add it to the $routeMiddleware
array.
Add the following line.
protected $routeMiddleware = [
'admin' => \App\Http\Middleware\CustomMiddleware::class,
];
This allows you to apply your middleware to specific routes.
Apply Middleware to Routes:
Now open your routes/web.php
or routes/api.php
file, and use the middleware method to protect your routes
Route::prefix('admin')->middleware(['admin'])->group(function () {
Route::get('/dashboard', [App\Http\Controllers\Admin\DashboardController::class, 'index']);
});
With this configuration, only users who pass the middleware check will be able to access the route.