7

I want to display a list of currently logged-in users in an app. I want to use Laravel Auth method. I'm looking at the API and I cannot find anything like it.

I would probably need to loop through the sessions store and then match it to a user ID. Am I right?

UPDATE: Forgot to mention, I'm storing sessions in the DB.

3 Answers 3

27

"Currently logged in" is something you can't do with plain old sessions. Let me explain why:

A session is a bunch of data stored at server side which is assigned to an user through a cookie. That cookie remains on user browser and so it keeps the session active. Sessions can stay "alive" months without the user even logging in.

But, it's possible to store sessions on database.

As you can see, Laravel keeps a field called last_activity and, through that field, you should be able to retrieve all sessions that had activity within the last 15 minutes (or something else, you call it).

When your retrieve those records, the data field is a serialized representation of session data. You can unserialize($session_record->data) and retrieve the user id.

Depending on your Auth driver, session's user id may have different names:

  • For eloquent driver, it should be eloquent_login.
  • For fluent driver fluent_login.
  • For your Custom\AuthClass, it should be called custom_authclass_login.
Sign up to request clarification or add additional context in comments.

5 Comments

Mission, can you be a bit more specific about your real doubt? We can then provide a more precise answer.
@vFragosop, he has no doubts, he just knew the details from your informative answer, and then said, huh, its easy and i knew about that, why bother then. Ignore him buddy, you had the best answer.
Sessions can NOT stay "alive" months - config('session.lifetime') has it set in minutes, by default it is 120 minutes.
@YevgeniyAfanasyev what happens if your session.lifetime is changed to 86400 minutes? It does stay alive for 60 days, doesn't it? So yes, sessions can stay alive for months.
I'm not using database for session, I use Redis. And I don't have last_activity. I guess that is why you can have the session records kept for months. Because no process there to delete the outdated records from the database. Redis cleans itself with different procedures. Thank you for the useful details about the case where the session data is kept in the database. I see now, I was wrong.
0

Assume that all http requests from logged in users are passing auth middleware, we can override terminate function like following:

public function terminate($request, $response)
{
    Auth::user()->save();
}

Then a query like User::where('updated_at', '>', Carbon::now()->subMinutes(12))->get(); will bring all logged in user, where 12 is the lifetime of session.

Of course, for real time, we should use ajax calls every 5 seconds or websockets via pusher or other.

1 Comment

pusher + Webhook, I mean.
-2

First create a table where the logged in user's id will be inserted

Schema::create('active_users', function(Blueprint $table)

{

                    $table->increments('id')->unsigned();
                    $table->integer('user_id')->unsigned();
                    $table->foreign('user_id')->references('id')->on('users')
                        ->onUpdate('cascade')->onDelete('cascade');

                    $table->timestamps();
        });

Then in yourcontroller insert data while logging in

if (Auth::attempt($credentials)) {

                  DB::table('active_users')->insert(array('user_id' =>   Auth::id()));
}

and delete the data while logging out

DB::table('active_users')->where('user_id', '=', Auth::id())->delete();

Print the online users list in your view

<ul><strong>Online Users</strong>
            <?php $online_users = DB::table('active_users')->where('user_id','!=',Auth::id())->get(); ?>

            @foreach($online_users as $online_user)
                <li>{{User::find($online_user->user_id)->first_name}}</li>
            @endforeach
        </ul>

3 Comments

What will happen when a session times out?
When session times out , delete the row from active_users table.
@PankajSuthar HOW ? ( When session times out , delete the row from active_users table. )

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.