Laravel Middleware
Laravel middleware is one of laravel's mechanisms. it handles all the HTTP requests. it means, when the user sends a request, at that time middleware verifies the request and whether it is authenticated or not. we normally use middleware to verify login authentication.
create middleware
You can create the middleware using the below php artisan command. after run the above command, The IsAdmin.php file will be created in the "app/Http/Middleware" directory. we need some changes in the handle method. so you can see the below code.<?php namespace App\Http\Middleware; use Closure; class IsAdmin { /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { if(auth()->user()->is_admin == 1){ return $next($request); } return redirect('home')->with('error',"You don't have admin access."); } } ?>
register middleware
After complete changes. we need to assign routes on the middleware array in the app/Http/Kernel.php file. so you can see the below code./** * The application's route middleware. * * These middleware may be assigned to groups or used individually. * * @var array */ protected $routeMiddleware = [ 'auth' => \App\Http\Middleware\Authenticate::class, 'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class, 'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class, 'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class, 'can' => \Illuminate\Auth\Middleware\Authorize::class, 'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class, 'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class, 'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class, 'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class, 'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class, 'is_admin' => \App\Http\Middleware\IsAdmin::class, ];
Middleware routes
Route::get('/', function () { return view('welcome'); }); Auth::routes(); Route::get('admin/home',[HomeController::class, 'adminHome'])->name('admin.home')->middleware('is_admin');