Open the file app/config/session.php
and change the driver
to database
.
We need to create the sessions
table, so use the following artisan command
php artisan session:table
to generate the migration file.
On this newly generated migration, you need to add a new user_id
column,
this is so we can relate the session to an user if that user is logged in.
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 mine
<?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');
}
}
Run php artisan dump-autoload
and php artisan migrate
.
Create a new model called Online.php
(you can rename it if you want) with the following
:
<?php
use Illuminate\Database\Eloquent\Model;
// use Sentry;
// use Session;
class Online extends Model {
/**
* {@inheritDoc}
*/
public $table = 'sessions';
/**
* {@inheritDoc}
*/
public $timestamps = false;
/**
* Returns all the guest users.
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @return \Illuminate\Database\Eloquent\Builder
*/
public function scopeGuests($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($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($query)
{
return $query->where('id', Session::getId())->update(array(
'user_id' => Sentry::check() ? Sentry::getUser()->id : null
));
}
/**
* Returns the user that belongs to this entry.
*
* @return \Cartalyst\Sentry\Users\EloquentUser
*/
public function user()
{
return $this->belongsTo('Cartalyst\Sentry\Users\EloquentUser'); # Sentry 3
// return $this->belongsTo('Cartalyst\Sentry\Users\Eloquent\User'); # Sentry 2
}
}
Must one use Sentry in order to make use of this? I am simply trying to show online registered and guest users and don't want to have to require more third party files if at all possible. Also, I do not see anywhere that a new session is created nor deleted.