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

  • SoldierCorp

    Cool, but.. how to apply it? i.e. Laravel register automatically every “what time” the last_activity of the user or how to works?

    Regards!

    • Hey there, well if you add it to the ‘before’ filter then it’s run every single time an auth user loads a route on your site. Therefore you know exactly when they last interacted with the application (whilst logged in).

      Does that make sense?

  • mrgingrich

    Very cool — works great. Thanks!

  • Nabil

    Cool, thanks

  • Sean

    When using the DateTime class you need to specify getTimestamp() or $now will simply return an Object instead of the intended (int)timestamp. Just change the line to $user->last_activity = $now->getTimestamp();

    • Thanks for the update Sean. Yeah I had written this for Laravel 3, so minor changes needed for L4. I must make a note of which version these posts were written for!

      • Sean

        You’re welcome, but thank you very much for writing this post as it was exactly what I was looking for.

  • Sean

    Another note for Laravel 4 users, the before filter is now App::before.

  • Pingback: Laravel change database data in filter.php | Programming area for everyone()