billok-lab's avatar

Login as user from admin panel

Hello guys,

How can I login as user from admin panel in laravel?

any help would be great :)

0 likes
8 replies
billok-lab's avatar

is it possible to do that without any package?

skoobi's avatar

The way I did it before I realised there was a package was to set a session of your user id (so you can set a button to log back in to the last user id i.e. admin), then in the controller Auth::logout(); followed by Auth::loginUsingId(3 ); then if you have a button that keeps the admin session id as a link to login back as the admin at the end.

So what its doing is logging out the current user but then login in using the provided user id. You can then redirect it to the correct page for the user

billok-lab's avatar

thank you for your explanation @skoobi, could you mind show me how you login as user from panel admin without any package?

skoobi's avatar

So this is a quick setup ::

    // Impersonates a user. User_id comes from a link
    public function impersonate($user_id)
    {
        session(['admin_id' => Auth::id()]);
        Auth::logout();
        Auth::loginUsingId($user_id);

        return redirect()->route('my-route');
    }

    // Sets it back to admin
    public function back_to_admin()
    {
        Auth::logout();
        Auth::loginUsingId(session('admin_id'));
	session()->forget('admin_id')

        return redirect()->route('my-route');
    }
1 like

Please or to participate in this conversation.