Source: ryangjchandler.co.uk

Track Your Users Last Activity in Laravel

Category: Laravel

Although there's many ways to do this in Laravel, the simplest way is with a piece of web middleware. When an authenticated user visits a route in our application, we want to store the timestamp in the database for use later on.

We also want to make sure this field is "fillable", so add last_active_at to the protected $fillable array on your User model. As well as being able to update last_active_at using User::update(), we want to cast it to a Carbon\Carbon instance when using it so that we can make use of time comparison methods.

If you want to track your users activity across all routes, it should be registered under the web array in App\Http\Kernel: If you only want to track the latest activity for particular routes, you can register the middleware as part of your route registration:
Newsletter

Get the latest Laravel/PHP jobs, events and curated articles straight to your inbox, once a week

Fathom Analytics | Fast, simple and privacy-focused website analytics. Fathom Analytics | Fast, simple and privacy-focused website analytics.
Achieve superior email deliverability with ToastMail! Our AI-driven tool warms up inboxes, monitors reputation, and ensures emails reach their intended destination. Sign up today for a spam-free future. Achieve superior email deliverability with ToastMail! Our AI-driven tool warms up inboxes, monitors reputation, and ensures emails reach their intended destination. Sign up today for a spam-free future.
Community Partners