Logged In User Count Laravel 3

226 Views Asked by At

I'm using Laravel 3. How do I have a notice that can tell me how many users are currently logged in.

I wish I could explain this better but I am new to Laravel and I should upgrade to 5.1 but that is not a option at the moment.

Any help is appreciated.

4

There are 4 best solutions below

1
Robbo On BEST ANSWER

Step 1: upgrade to Laravel 5.x
Step 2: add a migration to add the column active_at as a date to the users table
Step 3: add a new HTTP middleware called ActiveUser
Step 4: in the middleware handle method:

if ($user = $request->user()) {
    $user->active_at = new \DateTime();
    $user->save();
}

Step 5: feed your baby dragon
Step 6: you can now get users by activity using the active_at column

3
Reflic On

I think that is not a built in feature in Laravel. You could add a column to your user table, something like a flag if the user is logged in or not.

Simply set that column to true, after authenticating of the user and to false when the user logs out again.

Where you need the number of logged in users, simply count the rows in the user table where that flag is set to true.

0
Fester On

As far as I know there is no easy way to achieve this. What you can do is show how many users have logged in in the last X minutes using the last logged in column in the users column. I admit, this isn't exactly what you're looking for but it might be the next best thing.

0
serdar.sanri On

There is no way to accomplish this with laravel or php without using a third party tool like html5 websockets ( ratchet, socket.io etc ) or javascript with ajax.

  • it is pretty easy and more reliable with websockets. you can create your server to handle connection/disconnection and keep record of sockets connected and emit a message to all connected sockets count of actively connected sockets. This will be real time and less transaction since websockets will only trigger when there is an activity ( someone logins/logouts ) but requires higher access level of control over server/machine in order to install node.js, socket.io and open a tcp port for communication.
  • second option is javascript with ajax. keep a column in users data table as last_online and update this data each time user browses any page in your site. Like put a code at the top/bottom of your each page and update this columns value with current time. secondly determine how much avarage time a visitor roughly spends on your each page. then create a ajax script where you show your onlines count and trigger it every x amount of time that you determined ( i.e every 30 secs ) on the other side of your code check how many people were online since your last check ( current time - x time ) for instance $query = "select count(id) total_online_last30 from users where last_check>='" . date( "Y-m-d H:i:s" , strtotime( date() . " +30 seconds") ) . "'" then print it out.