DEV Community

Cover image for Laravel 8 Logout Other Devices after Login
Code And Deploy
Code And Deploy

Posted on • Updated on

Laravel 8 Logout Other Devices after Login

Originally posted @ https://codeanddeploy.com visit and download the sample code: https://codeanddeploy.com/blog/laravel/laravel-8-logout-other-devices-after-login

Advanced Laravel SAAS Starter Kit with CRUD Generator

Advanced Laravel SAAS Starter Kit with CRUD Generator - GET YOUR COPY NOW!

In this post, I will share an effective method provided by Laravel 8 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);
}
Enter fullscreen mode Exit fullscreen mode

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();
}
Enter fullscreen mode Exit fullscreen mode

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.

Advanced Laravel SAAS Starter Kit with CRUD Generator

Advanced Laravel SAAS Starter Kit with CRUD Generator - GET YOUR COPY NOW!

I hope this tutorial can help you. Kindly visit here https://codeanddeploy.com/blog/laravel/laravel-8-logout-other-devices-after-login if you want to download this code.

Happy coding :)

Top comments (0)