
Middleware for Admin in Laravel
In this article, you will learn, how to create a middleware for admin in Laravel. It will be useful for you to protect your admin routes from unauthorized access.
First, you need to run the following command at the root of your project:
php artisan make:middleware Admin
This will create a file at app/Http/Middleware/Admin.php. You need to write the following code in it:
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
class Admin
{
/**
* Handle an incoming request.
*
* @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next
*/
public function handle(Request $request, Closure $next): Response
{
if (auth()->check())
{
$user = auth()->user();
if (in_array($user->type, ["admin", "super_admin"]))
{
return $next($request);
}
}
return redirect("/admin/login");
}
}
- auth()->check()
- This will first check if the user is logged-in.
- $user = auth()->user();
- Then it get’s the logged-in user.
- in_array($user->type, [“admin”, “super_admin”])
- Then it checks if the user is either an admin or a super admin. Other type of users won’t be able to pass through it.
- return $next($request);
- This will stop the middleware from further execution and continue with the request to the next middleware or to the route.
- return redirect(“/admin/login”);
- If the user is not logged-in, or if he is not an admin or super admin, then he will be redirected to admin login page.
Now your middleware has been created, how to use it ?
You can use it in your routes/web.php or in your routes/api.php files.
use App\Http\Middleware\Admin;
Route::group([
"middleware" => [Admin::class]
], function () {
Route::get("/admin", [AdminController::class, "index"]);
});
We are grouping all the routes for admin in 1 place. Then we are applying our middleware to the entire group. This will protect all the routes inside it. So it’s super easy, highly customizable. I have used it in my 2 SAAS applications:
And it worked pretty good in terms of security. You can try and apply it in your project and let me know if you face any problem in this.