How to authenticate admin users in Laravel ?

Updated at 02-Mar-2022, By samar

How to authenticate admin users in Laravel ?

Good day, guys. In this post, we’ll look at how to solve the "How to authenticate admin users in Laravel ?" programming puzzle.

To authenticate admin users you have to create an admin middleware. Now you have to add code in it to redirect the user to the dashboard if authenticated user type is admin. To get the user type you have to add a column in users table and on the basis of user type authenticate the users to dashboard in Laravel
  • Create Admin middleware to authenticate admin users

    //1. Create middleware to authenticate admin users using php artisan command</span></p>
    php artisan make:middleware Admin
    
    //2. Edit middleware Admin.php
    //app\Http\Middleware\Admin.php</strong></p>
    public function handle($request, Closure $next)
    {
        if (Auth::check() && Auth::user()->user_type == 'admin') 
        {
            return $next($request);
        }
        
        else {
            return redirect('/');
        }
    }
    
    //3. <span style="font-weight: 400;">Add it to the routeMiddleware array in your kernel file
    //app/http/Kernel.php
    protected $routeMiddleware = [
        'admin' => 'App\Http\Middleware\Admin',
    ];
      
    //4. <span style="font-weight: 400;">Use Admin middleware to Route group
    //routes\web.php
    Route::middleware(['admin'])->group(function () {
        Route::get('admin/dashboard', '[email protected]')->name('admin.dashboard');
    });
    

Back to code snippet queries related laravel