Tracking If a User Is Currently Online in Laravel
Today I was tasked with adding a little green dot next to a username, denoting if they are online or not, on a user profile page, in a Laravel app. My first thought was that we were going to need to spin up a node.js server and track of active socket connections for each user. Then with the currently logged in users socket, we can update online status in real time! The only issue is that this was a little bit over the top for our current requirement, and was not completely necessary until we have features that require up to the second accuracy such as real-time chat.
A colleague pointed out that for the current need, the way that MySpace used to handle the “online” feature may be sufficient. To the best of our knowledge, the way that MySpace used to display if a user was online or not was based on their last activity on the site. If their last activity was within X minutes, we display the “online” badge, and if not, we don’t. Simple!
Let’s just add a column to the users table for that user’s last activity, and update that on every page request. Then when we need to check if the user is online, we can compare that timestamp with the current timestamp, and if it is within X minutes, they are online! While that would work just fine, depending on the application you are building, it adds unnecessary “writes” to the database, which could at some point slow down your application as you scale. A great compromise would be to store this information in the application cache. The great thing about the cache is that it simplifies this method because the cache can be set to expire.
Now that we decided we are going to implement this feature using the cache, the next question is where should this code go so that it runs on every request? I had two thoughts on where this should go:
- the constructor to the BaseController, that all of your application controllers extend
- a middleware
After some thought, and realizing that I would need to go and add calls to the parent constructor in all my already written constructors, I opted to try this out in a middleware.
We have a plan, so let’s get into the code!
First is to create the middleware, so from the terminal let’s run:
Originally published at www.laravelfeed.com.