I use Laravel 5.2.
I want to know how can I force a user to logout by id?
I'm building an admin panel with the option to dis-active specific user that are currently logged in to the web application.
Laravel gives you the this option for current user:
Auth::logout()
But I don't want to logout the current user, as I am that Auth user. I need to force logout a specific user by its id
. Just like when we login a user with specific id:
Auth::loginUsingId($id);
Is there something like this:
Auth::logoutUsingId($id);
Use the setUser to find a soluion
get current user
logout user you want to, by id
set again current user
I suggest you to override App\Http\Middleware\Authenticate handle function with custom check
Currently, there's no straightforward way to do this; As the
StatefulGuard
contract and itsSessionGuard
implementation don't offer alogoutUsingId()
as they do for login.You need to add a new field to your users table and set it to true when you want a specific user to be logged out. Then use a middleware to check if the current user needs a force logout.
Here's a quick implementation.
1. Add a new field
Let's add a new field to users table migration class:
Make sure you run
php artisan migrate:refresh [--seed]
after changing the migration.2. Force logout middleware
Let's create a new middleware:
Here's the logic to check if a user needs to be kicked out:
3. Register the middleware in HTTP kernel
Open up the
app/Http/Kernel.php
and add your middleware's FQN:It's untested code, but it should give you the idea. It'd be a good practice to add a couple of API methods to your
User
model to accompany with this functionality:markedForLogout()
: Checks user'slogout
flag.markForLogout()
: Sets user'slogout
flag totrue
.unmarkForLogout()
: Sets user'slogout
flag tofalse
.Then on the administration side (I suppose it's your case), you just need to call
markForLogout()
on the specific user model to kick him out on the next request. Or you can utilize the query builder to set the flag, if the model object is not available:It can be a
markForLogoutById($id)
method.Related discussions
[Proposal] Log out users by ID
Multiple statements when logged users are deleted