Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel login as another user

I am currently developing a laravel app where there are 3 user_roles

  1. Superadmin
  2. Admin
  3. Normal

So each role can access the roles below him.

e.g

Superadmins can access admins and normal users account.

How do I allow a authenticated superadmin user to log in as an admin or normal user with a click of a button?

USER_ROLES TABLE
id      name
 1      superadmin
 2      admin
 3      normal

----------------------------
USERS TABLE
id      first_name        last_name        user_role_id    password
 1      john              doe              1               *******
 2      jane              doe              2               *******
 3      cassie            snow             3               *******
 4      sansa             stark            3               *******
like image 410
Paul Ryan Lucero Avatar asked Aug 16 '17 04:08

Paul Ryan Lucero


1 Answers

You can use the following methods to log in any user

$userId = 1;
Auth::loginUsingId($userId, true);

or

$user = User::find(1);
Auth::login($user);

If you have set up roles in your user model you could use something like

    //check if the current user is superadmin
    $userRoles = Auth::user()->getRoleNames()->toArray();
        if (in_array('superadmin', $userRoles)) {
             //login the user
             Auth::login($user);          
        }
like image 110
Mister Verleg Avatar answered Oct 06 '22 10:10

Mister Verleg