Laravel, get currently registered users

I want to display a list of registered users in the application. I want to use the Laravel Auth method. I am looking at an API and I cannot find anything like it.

I will probably need to scroll through the session store and then map it to the user id. I'm right?

UPDATE: Forgot to mention, I store sessions in the database.

+4
source share
2 answers

β€œCurrent logon” is something you cannot do with regular old sessions. Let me explain why:

A session is a collection of data stored on the server side that is assigned to the user through a cookie. This cookie remains in the user's browser, so it keeps the session active. Sessions can remain live months without user intervention.

But it is possible to store sessions in a database .

As you can see, Laravel holds a field called last_activity , and through this field you can get all the sessions that have been active in the last 15 minutes (or something else, you name it).

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

Depending on your Auth driver, the session user ID may have different names:

  • For an eloquent driver, this should be eloquent_login .
  • For the free fluent_login driver.
  • For your Custom\AuthClass it should be called custom_authclass_login .
+18
source

First, create a table into which the input user 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 insert data into your controller during login

 if (Auth::attempt($credentials)) { DB::table('active_users')->insert(array('user_id' => Auth::id())); } 

and delete data during exit

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

Print a list of online users 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> 
-2
source

All Articles