How to get all users currently logged in to Laravel 5.4

Asked

Viewed 2,006 times

1

I need to loop all users who are currently logged in to the system. How could I do that? I know with auth()->check() we can know if a user is logged in. More I wanted to know of everyone who is currently logged in. There is a way?

1 answer

1

This is a very basic way, but I hope it will be effective.

Step 1

Open the file config/session.php and change the driver to the database (database).

Step 2

We need to create the session table, so use the following command artisan - php artisan session:table to generate the migration file.

Step 3

About this newly generated migration, you need to add a new column user_id, is how we can relate to session with a user, if that user is logged in, of course.

Open the file migrations/xxxx_xx_xx_xxxxxx_create_session_table.php and add the following inside the Schema::create:

$t->integer('user_id')->nullable();

Here is like the migration complete must be:

<?php

use Illuminate\Database\Migrations\Migration;

class CreateSessionTable extends Migration {

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('sessions', function($t) 
        {
            $t->string('id')->unique();
            $t->text('payload');
            $t->integer('last_activity');
            $t->integer('user_id')->nullable();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('sessions');
    }

}

Step 4

Execute composer dump-autoload and php artisan migrate.

Note: If you don’t have Composer installed globally, just use php composer.phar dump-autoload.

Step 5

Save the Model Eloquent somewhere in its application as Session.php.

Note: The recommended location to save this is in the application directory.

Step 6

Now you just need to know how to use it.

. . .

Use

Put the following Session::updateCurrent(); somewhere in your code as this will ensure that the session entry for the current user is updated, just an example, you can put it in your file app/routes.php.

Get all users

$all = Session::all();

If you need to check all users online for a certain period, like 10 minutes, you need to call the method activity(:limit), thus:

$all = Session::activity(10)->get();

Note: This method can be used in combination with guest() and/or Registered methods().

Guest users

Get everyone

$guests = Session::guests()->get();
Get the # of Guest users

$total = Session::guests()->count();

Registered users

Get everyone

$registered = Session::registered()->get();

foreach ($registered as $online) {
    // You can retrieve the user information using something like:
    var_dump($online->user->email);
}

Get the number of registered users

$total = Session::registered()->count();

Modelo Eloquent

use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Session;
use Illuminate\Database\Eloquent\Builder;
use Cartalyst\Sentinel\Laravel\Facades\Sentinel;

class Session extends Model 
{
    /**
     * {@inheritdoc}
     */
    public $table = 'sessions';

    /**
     * {@inheritdoc}
     */
    public $timestamps = false;

    /**
     * Returns the user that belongs to this entry.
     *
     * @return \Cartalyst\Sentinel\Users\EloquentUser
     */
    public function user()
    {
        return $this->belongsTo('Cartalyst\Sentinel\Users\EloquentUser');
    }

    /**
     * Returns all the users within the given activity.
     *
     * @param  \Illuminate\Database\Eloquent\Builder  $query
     * @param  int  $limit
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopeActivity($query, $limit = 10)
    {
        $lastActivity = strtotime(Carbon::now()->subMinutes($limit));

        return $query->where('last_activity', '>=', $lastActivity);
    }

    /**
     * Returns all the guest users.
     *
     * @param  \Illuminate\Database\Eloquent\Builder  $query
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopeGuests(Builder $query)
    {
        return $query->whereNull('user_id');
    }

    /**
     * Returns all the registered users.
     *
     * @param  \Illuminate\Database\Eloquent\Builder  $query
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopeRegistered(Builder $query)
    {
        return $query->whereNotNull('user_id')->with('user');
    }

    /**
     * Updates the session of the current user.
     *
     * @param  \Illuminate\Database\Eloquent\Builder  $query
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopeUpdateCurrent(Builder $query)
    {
        $user = Sentinel::check();

        return $query->where('id', Session::getId())->update([
            'user_id' => $user ? $user->id : null
        ]);
    }
}

Alternatively, you can try that.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.