Table of contents

laravel logout other devices after login

In this post, I will share an effective method provided by Laravel 8, 9 on how to log out other devices after login. If your developing a Laravel project that has a subscription limit to the users and is only allowed to login into one device at a time then we must implement this method.

 

If your using the default login method by Laravel then follow the steps below:

 

First, in your LoginController we have a method named login(). See the example code below:

 

/**
* Handle account login request
* 
* @param LoginRequest $request
* 
* @return \Illuminate\Http\Response
*/
public function login(LoginRequest $request)
{
    $credentials = $request->getCredentials();

    if(!Auth::validate($credentials)):
        return redirect()->to('login')
             ->withErrors(trans('auth.failed'));
    endif;

    $user = Auth::getProvider()->retrieveByCredentials($credentials);

    Auth::login($user, $request->get('remember'));

    if($request->get('remember')):
        $this->setRememberMeExpiration($user);
    endif;

    return $this->authenticated($request, $user);
}

 

As you can see in my example we returned the authenticated() method after no errors above codes.

 

Then we should have an authenticated() method in our LoginController, See the example below:

/**
* Handle response after user authenticated
* 
* @param Request $request
* @param Auth $user
* 
* @return \Illuminate\Http\Response
*/
protected function authenticated(Request $request, $user) 
{   
    Auth::logoutOtherDevices($request('password'));

    return redirect()->intended();
}

 

As you can see I added Auth::logoutOtherDevices() with the parameter of password. So that we can enable to log out of the other active devices.

 

I hope it helps. Thanks for reading :)

 

Cheers :)