Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Fawwad's avatar

How to check user role after login?

I am using laravel 5.3. There are roles(rid,name),users_roles(uid,rid). Now how to check user role on login and redirect according to role id i.e, if user is admin it goes to admin dashboard other wise it will redirect to dashboard.

0 likes
11 replies
rodrigo.pedra's avatar

I generally add a home route to redirect the users to theirs proper "home" based on some sort of role, something like this:

<?php
// routes/web.php

Route::get('home', 'HomeController@redirect')
    ->name('home'); // I usually add the name so I can use the route(...) helper

Then in your HomeController:

<?php

namespace App\Http\Controllers;

class HomeController extends Controller
{
    public function redirect()
    {
        if (! auth()->check() ) {
            return redirect()->to( '/auth/login' );
        }

        if (auth()->user()->is_admin) {
            return redirect()->to( '/admin-dashboard' );
        }

        return redirect()->to( '/dashboard' );
    }
}

If you are sure that you only need to redirect the user on login, there is an easier path, just override the authenticated(...) in your Auth\LoginController, like so:

<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;

class LoginController extends Controller
{
    use AuthenticatesUsers;

    // protected $redirectTo = '/home'; // will be overriden by the authenticated method

    public function __construct()
    {
        $this->middleware('guest')->except('logout');
    }

    /**
     * The user has been authenticated.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  mixed  $user
     * @return mixed
     */
    protected function authenticated(Request $request, $user)
    {
        if ($user->is_admin) {
            return redirect()->to('/admin-dashboard');
        }

        return redirect()->to('/dashboard');
    }
}
RamjithAp's avatar

Go to your App/http/controllers/auth/AuthController.php add this function

protected function authenticated(Request $request, $user)
   {
    $uid =  $user->id;
    $role= \DB::table('users_roles')
        ->where('users_roles.uid','=',$uid)
        ->join('roles', 'users_roles.rid', '=', 'roles.rid')
        ->select('roles.name as name')
        ->first();
    if ($role->name=='admin') {
        return redirect('/admindashbaord');
    } elseif($role->name=='manager') {
        return redirect('/managerdashbaord');
    }
   }

Alternatively, you can check the user role & redirect on your dashboard controller where the user goes to after login as well.

1 like
robrogers3's avatar

well on login the default is to take you to /home, right?

you need to create views (dashboards) for each of your roles:

/admin-dashboard /manager-dashboard /other-role-dashboard

next create routes for each of those pages

example

Route::get('/dashboard', function() {
    return view('dashboard');
})

now go to your LoginController and add a method

public function redirecTo()
{
    $role = auth()->user()->role;
    
    $path = $role->getPathForRole();

    return redirect($path);

}

done

1 like
Fawwad's avatar

I did not create extra column(role) in users table. I did create separate tables for role in which i put role id and role name (admin,manager). In users_role table columns are user id, role id. So what is the best way to check user role just after logged in. I mean it will be middleware or controller. Please suggest me.

RamjithAp's avatar

Check my reply that's why I used DB query to get the user role from another table and based on it redirect.

rodrigo.pedra's avatar

@Fawwad you can make the DB call as @RamjithAp suggested or you can keep the code I showed and have an accessor to check if the user has that role, even in other table:

<?php

namespace App;

use App\Role;
use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    public function getIsAdminAttribute()
    {
        return $this->roles->where('name', 'admin')->count() > 0;
    }

    public function roles()
    {
        return $this->belongsToMany( Role::class, 'users_role' );
    }
}

Check the docs on accessors at: https://laravel.com/docs/5.5/eloquent-mutators#accessors-and-mutators

Fawwad's avatar

Below is my code

namespace App\Http\Controllers;

use Illuminate\Http\Request; use Auth; use Input; use Validator; use Redirect; class LoginController extends Controller { // public function login_post(Request $request){

  $data=Input::except(array('_token'));
  //var_dump($data);
  $rule=array(
    'email'=>'required|email',
    'password'=> 'required',
  );

  $validator=Validator::make($data,$rule);
  if($validator->fails()){

  }else{
    $data=Input::except(array('_token'));
    if(Auth::attempt($data)){
       //here i want to check logged in user role
      return Redirect::to('/dashboard');
    }

  }

}

}

1 like
RamjithAp's avatar
namespace App\Http\Controllers;

use Illuminate\Http\Request; 
use Auth;
use Input;
use Validator;
use Redirect;

 class LoginController extends Controller { 

  public function login_post(Request $request){

  $data=Input::except(array('_token'));
  //var_dump($data);
  $rule=array(
    'email'=>'required|email',
    'password'=> 'required',
  );

  $validator=Validator::make($data,$rule);
  if($validator->fails()){

  }else{
    $data=Input::except(array('_token'));
    if(Auth::attempt($data)){
        $uid =  Auth::User()->id;
        $role= \DB::table('users_roles')
        ->where('users_roles.uid','=',$uid)
        ->join('roles', 'users_roles.rid', '=', 'roles.rid')
        ->select('roles.name as name')
        ->first();
       if ($role->name=='admin') {
        return redirect('/admindashbaord');
        } elseif($role->name=='manager') {
        return redirect('/managerdashbaord');
        }
    }

  }

}
}
1 like
rodrigo.pedra's avatar
Level 56

I would create the roles relationship in the user model, so it is easily reused:

<?php

namespace App;

use App\Role;
use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    public function getIsAdminAttribute()
    {
        return $this->roles->pluck( 'name' )->contains( 'admin' );
    }

    public function roles()
    {
        // you will need a role model
        // Role::class is equivalent to string 'App\Role'
        return $this->belongsToMany( Role::class, 'users_role' );
    }
}

Then in your LoginController:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Auth;
use Input;
use Validator;
use Redirect;

class LoginController extends Controller
{
    //
    
    public function login_post( Request $request )
    {
        $data = Input::except( array( '_token' ) );

        // var_dump($data);

        $rule = array(
            'email'    => 'required|email',
            'password' => 'required',
        );

        $validator = Validator::make( $data, $rule );

        if ($validator->fails()) {
            // should do something
        } else {
            // no need to populate $data again with the same values
            // $data = Input::except( array( '_token' ) );
            
            if (Auth::attempt( $data )) {
                // here i want to check logged in user role
                $user = Auth::user();
                
                if ($user->roles->pluck( 'name' )->contains( 'admin' )) {
                    return Redirect::to( '/admin-dashboard' );
                }
                
                return Redirect::to( '/dashboard' );
            }
        }
    }
}

But if you don't need a role model, go for @RamjithAp solution, we are basically doing the same but with different approaches.

I prefer to avoid using the DB facade if I have a chance to use Eloquent for reusability.

But the best is to do something you are comfortable with and understand better.

1 like
mohamednagy's avatar

You can simply use one of the access layer packages, there are many packages that can handle user roles and permissions. This package can do the job :)

https://github.com/mohamednagy/Permissions-Handler

$user = Auth::user();
if ($user->hasRole('admin' )) {
    return redirect('admin-view');
} 

if ($user->hasRole('user' )) {
    return redirect('user-view');
} 

Please or to participate in this conversation.