简体   繁体   中英

Laravel : Check if another user is currently logged in

I'm speaking about a simple laravel's 4.2 web site with authentication system.

I am user A (super-user), and I want to see if user B or/and user C (and all other users) are logged in. Is there any built in function (something with Auth class) to do this ?

You can't say for sure if a user B/C is logged in. But you can guess if a user is logged in. If you remember the last action of user B/C and you know the timeout until a user gets logged out automatically this would give you an estimate value if the user is still logged in or not.

Add a migration for your users table and add a new field to your table

$table->timestamp('last_activity')->nullable();

Add a before filter

App::before(function ($request) {
    if (Auth::user()) {
        $user = Auth::user();
        $now = new DateTime();
        $user->last_activity = $now->getTimestamp();
        $user->save();
    }
});

Now you can check when the last action of user B/C was and if this is within the auto logout time it is possible that the user is still logged in. If not the user is definitely logged out.

In case you want to log users activity there is a package Regulus343/ActivityLog .

It's easy but you can only check one person at time which means it's not possible to use complex conditions for example count all logged in users. If you want to check if a user other than you is logged in, use a helper function like this.


<?php 
// Helper.php

    public function isLoggedIn($user_id)
    {
        if(Auth::check())
        {
            return $user_id == Auth::user()->id;
        }
    }  

?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM