LARAVEL MIDDLEWARE
Overview
-
Laravel Default Middleware
Actually, Laravel has some default middleware that can be used to protect your routes. Like
auth,verified,guest,throttle, etc. But, how if you have case that need custom middleware? You must create your own middleware right? -
Case Study
For example, you have a case that need to check if the user is admin or not. You can create a middleware to check if the user is admin or not.
-
Users Table
For this case, in users table, you have a column
rolethat contains the user role. If the user role isadmin, then the user is authorized to access the resource.| id | name | email | role | | --- | ---- | ------------------ | ----- | | 1 | John | [email protected] | admin | | 2 | Jane | [email protected] | user |
Create Middleware
-
Create Middleware
php artisan make:middleware CheckAdmin -
Edit Middleware
// app/Http/Middleware/CheckAdmin.php namespace App\Http\Middleware; use Closure; use Illuminate\Http\Request; class CheckAdmin { public function handle(Request $request, Closure $next) { if (auth()->user()->role !== 'admin') { return response()->json(['message' => 'You are not authorized to access this resource'], 403); } return $next($request); } } -
Register Middleware
Add the middleware to the
$routeMiddlewareproperty of yourapp/Http/Kernel.phpfile.// app/Http/Kernel.php protected $routeMiddleware = [ 'isAdmin' => \App\Http\Middleware\CheckAdmin::class, ]; -
Use Middleware
You can use the middleware in your routes
Route::get('/admin/user-management', UserManagementController::class)->middleware('isAdmin');Or you can use it in your controller constructor
// Controller public function __construct() { $this->middleware('isAdmin'); } // Route Route::get('/admin/user-management', UserManagementController::class);
Explanation
php artisan make:middleware CheckAdminis used to create a new middleware namedCheckAdmin.- In the
handlemethod of the middleware, we check if the authenticated user's role is not equal toadmin. If it is not, we return a JSON response with a403status code. - The
$next($request)method is used to pass the request - The middleware is registered in the
$routeMiddlewareproperty of theapp/Http/Kernel.phpfile. - The middleware can be applied to routes using the
middlewaremethod or in the controller constructor.