My goal is to check all user(s) in my users table to see if they're online using Laravel 4
. I'm also interested in who's not logged-in as well. Later on, I want to print out 2 separate lists of who's online and who's not ?
Auth::check()
that came with Laravel ?database
?Sample
I want to suggest some logics to you.
After you have that,
In your Sign-In function, somewhere at the end before you redirect.
set is_online = '1';
// this should be save into your database now.
Apply the same similar logic in your Sign-Out function,somewhere at the end before you redirect.
set is_online = '0';
Don't forget to save !! by doing $user->save();
any time you update any info on your database.
Print your list You can do
For all the user()->is_online = '1' OR user()->is_online = '0'
// Do any programming logic with it, print it or whatever ...
Give it a try ! if you stuck, post some code, I will help you through it.
There is no way to know if the user is still on your website. You can only use some ways to guess if they are.
The most commonly used way is by saving the timestamp on which a user last visited a page. If you say that a user stays on one page for one minute you can say that the user is online if there is less then one minute time between the last timestamp and the current timestamp.
Facebook uses a sort of ping function to check this. They send an ajax request to the server every x seconds. That way they know the user is still on the website.
I recently had the same question and solved it the following way (Laravel 5):
class AddLastOnlineToUsersTable extends Migration { public function up() { Schema::table('users', function (Blueprint $table) { $table->dateTime('last_online'); }); } public function down() { Schema::table('users', function (Blueprint $table) { $table->dropColumn('last_online'); }); }
Don't forget to add the new field to the $fillable and $dates arrays in the User model.
abstract class Controller extends BaseController { public function __construct() { $this->user = Auth::user(); if($this->user) { $this->user->last_online = Carbon::now(); $this->user->save(); } } }
public function getAllUsersOnline($seconds_since_last_activity = 300) { $last_activity = Carbon::now()->subSeconds($seconds_since_last_activity); $online_users = User::where('last_online', '>=', $last_activity)->get(['id', 'user_name']); return $online_users; }