Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@jeremykenedy
Created November 29, 2015 11:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jeremykenedy/b49df73ed5d384955085 to your computer and use it in GitHub Desktop.
Save jeremykenedy/b49df73ed5d384955085 to your computer and use it in GitHub Desktop.
Sentinel Logged in Users for Laravel 4 and Laravel 5

Sentinel Logged in Users for Laravel

This is a very basic, but hopefully an efective way to detect both Guest and Registered users on your Laravel application.

The Usage and the Eloquent Model are basically the same on both Laravel 4 and Laravel 5, just the installation differs, since the application structure is different.

Please refer to one of the following links for installation on Laravel 4 or on Laravel 5.

Laravel 4

Step 1

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

Step 2

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

Step 3

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

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

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

Here is how the full migration should look:

<?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

Run php artisan dump-autoload and php artisan migrate.

Step 5

Save the Eloquent Model somewhere on your application as Session.php.

Note: The recommended place to save this is on the app/Models directory.

Step 6

Now you just need to know how to use it.

Laravel 5

Step 1

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

Step 2

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

Step 3

On this newly generated migration, you need to add a new user_id column, this is so we can relate the session to 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 how the full migration should look:

<?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

Run 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 Eloquent Model somewhere on your application as Session.php.

Note: The recommended place to save this is on the app directory.

Step 6

Now you just need to know how to use it.

<?php

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
        ]);
    }
}

Usage

Place the following Session::updateCurrent(); somewhere on your code, as this will make sure that the session entry for the current user get's updated, just an example, you can place it on your app/routes.php file.

Get all users (Guests + Registered)

$all = Session::all();

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

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

Note: This method can be used in combination with the guests() and/or registered() methods.

Guest Users

Grab all

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

Registered Users

Grab all

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

foreach ($registered as $online) {
    // You can retrieve the user information using something like:
    var_dump($online->user->email);
}
Get the # of Registered users
$total = Session::registered()->count();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment