Table of contents
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 :)
Read next