Laravel: Tracking last activity date of authorised user

Sometimes it’s useful to record when an authorised user was last active in your web application – whether it’s something that you show on the front end to other users, or whether you want to have an admin feature to track possibly inactive users.

Fortunately it’s incredibly simple to implement.

Add column to users table

First up you’ll need to add a column to your users table.

In your migrations file for the users table just add the following.

$table->timestamp('last_activity')->nullable();

This needs to go in Schema::create in your ‘up’ function.

Alter your ‘before’ route

Route::filter('before', function()
{
	if (Auth::user()) {
		$user = Auth::user();
		$now = new DateTime();
		$user->last_activity = $now;
		$user->save();
	}
});

That’s all there is to it. Now when a user is logged in we’ll quickly update their ‘last_activity’ column with the correct timestamp.

Comments