Log user activity in Laravel 5.6

laravel activitylog

In this article, we will log the user activity in our table using laravel-activity package. The spatie/laravel-activity package provides easy to use functions to log the activities of the users of your application. It can also automatically log model events. All activity will be stored in the activity_log table.

Let’s get started.

Step 1: Install Package

First of all, you need to install spatie/laravel-activity package. To do this, simply run the following command in your terminal.

Please note that, this package is a bit strict in requirements and require PHP 7.0+ and Laravel 5.5+ for latest version (v2) OR laravel 5.2+ for previous version (v1)

Publish Migration

After downloading package, you need to publish migration. You can publish migration with following command:


Now, create table activity_log table with command:

Publish Config

You can optionally publish the config file by running below command:

This command will publish your package configuration file. It’s default configuration looks like below:

Step 2: Using Activity Log

The basic usage of this package can be done like below:

This will logged your record in activity_log table. In this way, you can logged anything in your database.

After this, you obviously need to retrieve your logged record. To do this, you can simply call your model as like below:

You can also specify the model on which activity is acted upon using below syntax:

You can can set the user who caused the activity log using causedBy:

You can also log other properties to activity_log table using withProperties

Step 3: Logging Model event

If you are working with large application or dynamic application, you mostly have to work with different models. This package make it simpler to log model event (created, updated and deleted). You can log this event using $logAttributes property on the model. For example:

Customizing logged events

You can customize events created, updated, deleted using $recordEvents property to model. For example:

Customizing logged description

You can customize logged description using getDescriptionForEvent() function. For example:

You can access the logged description as like below:

Model Event logging using boot() function

You can logged model event using boot() function in model. For example, I have logged newly created user detail and deleted user detail in activity log where User.php is a user model.

I hope you have gained pretty much knowledge about using this package. You can find more about this package in it’s official documentation.