Log user activity in Laravel 5.6

0
10945
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.

composer require spatie/laravel-activitylog

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:

php artisan vendor:publish --provider="Spatie\Activitylog\ActivitylogServiceProvider" --tag="migrations"

Migrate

Now, create table activity_log table with command:

php artisan migrate

Publish Config

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

php artisan vendor:publish --provider="Spatie\Activitylog\ActivitylogServiceProvider" --tag="config"

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

return [

    /*
     * When set to false, no activities will be saved to database.
     */
    'enabled' => env('ACTIVITY_LOGGER_ENABLED', true),

    /**
     * When running the clean-command all recording activities older than
     * the number of days specified here will be deleted.
     */
    'delete_records_older_than_days' => 365,

    /**
     * When not specifying a log name when logging activity
     * we'll using this log name.
     */
    'default_log_name' => 'default',

    /**
     * You can specify an auth driver here that gets user models.
     * When this is null we'll use the default Laravel auth driver.
     */
    'default_auth_driver' => null,

    /**
     * When set to true, the subject returns soft deleted models.
     */
     'subject_returns_soft_deleted_models' => false,

    /**
     * This model will be used to log activity. The only requirement is that
     * it should be or extend the Spatie\Activitylog\Models\Activity model.
     */
    'activity_model' => \Spatie\Activitylog\Models\Activity::class,
];

Step 2: Using Activity Log

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

activity()->log('Hey!, I logged something');

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:

$lastActivity = Activity::all()->last(); //returns the last logged activity

$lastActivity->description; //returns 'Hey!, I logged something';

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

activity()
   ->performedOn($someContentModel)
   ->log('edited');

$lastActivity = Activity::all()->last(); //returns the last logged activity

$lastActivity->subject; //returns the model that was passed to `performedOn`;

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

activity()
   ->causedBy($userModel)
   ->performedOn($someContentModel)
   ->log('edited');

$lastActivity = Activity::all()->last(); //returns the last logged activity

$lastActivity->causer; //returns the model that was passed to `causedBy`;

You can also log other properties to activity_log table using withProperties

activity()
   ->causedBy($userModel)
   ->performedOn($someContentModel)
   ->withProperties(['key' => 'value'])
   ->log('edited');

$lastActivity = Activity::all()->last(); //returns the last logged activity

$lastActivity->getExtraProperty('key') //returns 'value';

$lastActivity->where('properties->key', 'value')->get(); // get all activity where the `key` custom property is 'value'

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:

use Illuminate\Database\Eloquent\Model;
use Spatie\Activitylog\Traits\LogsActivity;

class NewsItem extends Model
{
    use LogsActivity;

    protected $fillable = ['name', 'text'];

    protected static $logAttributes = ['name', 'text'];
}

Customizing logged events

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

use Illuminate\Database\Eloquent\Model;
use Spatie\Activitylog\Traits\LogsActivity;

class NewsItem extends Model
{
    use LogsActivity;

    //only the `deleted` event will get logged automatically
    protected static $recordEvents = ['deleted'];
}

Customizing logged description

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

use Illuminate\Database\Eloquent\Model;
use Spatie\Activitylog\Traits\LogsActivity;

class NewsItem extends Model
{
    use LogsActivity;

    protected $fillable = ['name', 'text'];

    public function getDescriptionForEvent(string $eventName): string
    {
        return "This model has been {$eventName}";
    }

}

You can access the logged description as like below:

//creating the newsItem will cause an activity being logged
$activity = Activity::all()->last();

$activity->description; //returns 'This model has been created'

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.

protected static function boot()
{
    parent::boot();

    static::creating(function ($user) {
       activity('user')
           ->performedOn($user)
           ->causedBy(user())
           ->withProperties([
                'user_id'    => $user->id,
                'first_name' => $user->first_name,
                'last_name'  => $user->last_name,
                'phone'      => $user->phone
             ])
           ->log('Account Created');
    });

    static::deleting(function ($user) {
       activity('user')
           ->performedOn($user)
           ->causedBy(user())
           ->withProperties([
                'user_id'    => $user->id,
                'first_name' => $user->first_name,
                'last_name'  => $user->last_name,
                'phone'      => $user->phone
            ])
           ->log('Account Deleted');
    });
}

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

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.