Lee Willis

Activity logging in Laravel


I’ve been working on a new service for the last month or so that enables people to log, track and share walks in the UK’s hills and mountains. The service is based on Laravel, and one of the things I wanted to include on the site was an “activity feed”.

There are two types of feed I wanted to create. The first was for my own benefit. I wanted to see a simple timeline of activity on the site as usage builds up. Secondly, I wanted to be able to log data so that I can create public timelines in the future.

This is all pretty simple to build from scratch, but it turns out that the team at Spatie have already got this covered with a general package for logging activity on a Laravel application.

You can easily log custom activity events wherever you like, it’s as easy as:

activity()->log('My custom message here');

Even better though is that you can get it to log changes to Eloquent models automatically using the handy LogsActivity trait. If you add the trait to your model, then creating, updating or deleting a model will automatically create a log entry. The log entries include the item affected, and the “causer” (normally a user).

Going beyond the basics, you can also define custom messages, choose what data to store along with log events.

The activities are logged as normal Eloquent models, so once you have your data logged it’s easy to pull out the information you need using standard Laravel querying, and views.

Leave a Reply

Required fields are marked *.