I want to be able to login as another user from my administrator account.
I'm making a SPA application with Inertia Js using laravel fortify to handle sessions and login.
In laravel 8 i was able to login as another user but with the laravel 9 the login method makes me logout.
$user = User::find(2);
Auth::guard('web')->login($user); // or // Auth::login($user);
I checked about the csrf token , i tried to exclude my uri but nothing changes.
If you have any idea don't hesitate thanks !
CodePudding user response:
Sometimes using the login feature programmatically in Laravel requires the session to be flushed before logging in as another user.
//IN CASE YOU WANT TO STORE THE ORIGINAL ADMIN USER FOR REVERTING THE SESSION
$adminUserId = auth()->user()->id;
//FLUSH THE SESSION SO THAT THE NEXT TIME LOGIN IS CALLED IT RUNS THROUGH ALL AUTH PROCEDURES
session()->flush();
//GET THE USER MODEL
$user = User::find(2);
//LOGIN AS THE USER
Auth::login($user);
//IN CASE YOU WANT TO STORE THE ORIGINAL ADMIN USER FOR REVERTING THE SESSION
session()->put('admin_user_id', $adminUserId);