Recording the ‘Last Seen’ timestamp

From here, there are two options to record the time of the last request for later retrieval. The first option which I would recommend is to use a key / value store such as Redis as it faster in write & read speed than a traditional database such as MYSQL or Postgres. However, if you are not using a key / value store, using the database will not in practicality add much overhead to request time and it’s best not to overthink it.

A note on the possibility of using queue jobs:

When first implementing the feature I thought to add it in a queue job so you wouldn't be writing to the DB on every request. However, if your queue driver is redis or the database then you will be writing to the database anyway and considering recording a timestamp does not carry much overhead, you may as well just write the timestamp in directly as it will carry the same overhead as creating a queue job without also crowding your queue.

Using Redis (Recommended)

Edit App\Http\Middleware\LastSeen.php to add the following code to record the time of the request

Then, to retrieve a user’s last seen time such as for your admin console, add this method to the user model.

public function lastSeen() {

$redis = Redis::connection();

return $redis->get('last_seen_' . $this->id);

}

You can then retrieve the last seen information on a user by calling the method as such:

$user->lastSeen();

To append the property to the user as a regular database property would appear change the name of the function to:

getLastSeenAttribute()

and add an $appends property to the user model like so:

protected $appends = ['lastSeen'];

Now you will always be able to call $user->lastSeen as you would for a regular model property.

Using the Database

To start with using the database we need to add a column to the user’s table.

Start by making the migration

php artisan make:migration addLastSeenToUser

Now edit the migration

Schema::table('users', function (Blueprint $table) { $table->dateTime('last_seen')->nullable(); });

And run this command to add the column to your database.

php artisan migrate

Now we have a column to input data into, lets edit App\Http\Middleware\LastSeen.php to add the following code to record the time of the request

To access the time of the last request, representing the last time they accessed your web app, simply retrieve the property like any other

$user->last_seen;

And that’s it! You are now ready to reduce churn by following up on those users dropping off. If you don’t measure it, you can’t manage it.

Follow me on Medium for more blog posts to get the most out of Laravel