Skip to content

Instantly share code, notes, and snippets.

@wadtech
Last active December 13, 2023 15:31
Show Gist options
  • Save wadtech/74b4363bf065245a2ef055dea6adfc72 to your computer and use it in GitHub Desktop.
Save wadtech/74b4363bf065245a2ef055dea6adfc72 to your computer and use it in GitHub Desktop.
Laravel 5.3 Custom Database Session Handler Example
<?php
namespace App\Extensions;
// we have an Eloquent model that allows using the session table with the querybuilder methods and eloquent fluent interface- read only!
use App\Session;
// use the provided database session handler to avoid too much duplicated effort.
use Illuminate\Session\DatabaseSessionHandler;
class AppDatabaseSessionHandler extends DatabaseSessionHandler
{
/**
* The destroy method can be called at any time for a single session. Ensure that our related records are removed to prevent foreign key constraint errors.
*
* {@inheritdoc}
*/
public function destroy($sessionId)
{
$session = $this->getQuery()->where('id', $sessionId);
// tidy up any orphaned records by this session going away.
$sessionModel = Session::find($sessionId);
foreach ($sessionModel->myModels as $model) {
$sessionModel->myModels()->detach($model->id);
$model->delete();
}
$session->delete();
}
/**
* Replicate the existing gc behaviour but call through to our modified destroy method instead of the default behaviour
*
* {@inheritdoc}
*/
public function gc($lifetime)
{
$sessions = $this->getQuery()->where('last_activity', '<=', time() - $lifetime)->get();
foreach ($sessions as $session) {
$this->destroy($session->id);
}
}
}
<?php
return [
'driver' => 'app-database',
// etc...
];
<?php
namespace App\Providers;
use App\Extensions\AppDatabaseSessionHandler;
use Illuminate\Support\ServiceProvider;
use Illuminate\Database\ConnectionInterface;
use Session;
use Config;
class SessionProvider extends ServiceProvider
{
/**
* Perform post-registration booting of services.
*
* @return void
*/
public function boot(ConnectionInterface $connection)
{
Session::extend('app-database', function($app) use ($connection) {
$table = Config::get('session.table');
$minutes = Config::get('session.lifetime');
return new AppDatabaseSessionHandler($connection, $table, $minutes);
});
}
/**
* Register bindings in the container.
*
* @return void
*/
public function register()
{
//
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment