display-user-devices-application-currently-logged-option-logout-laravel

Display user devices there application is currently logged in and option to logout in Laravel

Often users login into an application from multiple devices, but forget to logout. Or sometimes they want to logout from a particular devices because of any reason whatsoever or they want to check the devices their application is currently logged in.

You might have seen similar features in facebook, twitter and many other applications, which allows you to see all browsers and devices from which you are currently logged in with options to logout from that device.

In this post we will look into implementing this feature in our Laravel application using session.

For doing it we have to make use of database session, it will not be possible (read hard and not recommended) to do it using File based session.

Enable Database Session in Laravel

  1. Change the ‘session’ driver present in /config/session.php to ‘database’ (or if you’re using .env file change inside it)
  2. Change the Session Database Connection key ‘connection’ in same file to mysql (or some other based on the connection used in database.php file)
  3. Create a table in database to store session related information by running:

    More on it here

Now if you look into the database, a sessions table is created which will be used to save all session related data (in payload field) with some meta data like (user_id, ip_address, user_agent, last_activity).

To show the list of all browsers and ip address simply run a query with a where condition for user_id field. Also in case you have set lifetime of session inside session.php file add a check for that comparing to ‘last_activity‘ field in sessions table.

With this you will get list of all browsers from which user has logged in.

To logout a user from a particular browser simply update the sessions tables ‘user_id’ field to Null or delete that particular row, with this the server will not able to identify the user from that browser.

Hope this is a helpful tip.
Do you have a better way of doing it ? or facing any issue with this solution ? Do share in the comments below.

Thanks 🙂

No Comments

Leave a comment

Your email address will not be published. Required fields are marked *