Site icon Student Projects Live

Laravel Activitylog Tutorial for Beginners

Laravel Activitylog Tutorial for Beginners

This is Laravel Activitylog Tutorial for Beginners. Tracking user actions is an important feature in modern web applications. Whether you want to know who updated a product, deleted a customer, or logged in, activity logs provide valuable information.

In this tutorial, you’ll learn how to use the Spatie Laravel Activitylog package to record activities in a Laravel application.

By the end of this guide, you’ll be able to:


Prerequisites

Before starting, you should have:


What is Laravel Activitylog?

Laravel Activitylog is a package that records activities happening inside your application.

Examples include:

Instead of creating your own logging system, this package handles it for you.


Step 1 — Install the Package

Run the following command:

composer require spatie/laravel-activitylog

Step 2 — Publish the Configuration

Publish the configuration and migration files.

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

This creates:

config/activitylog.php

and a migration file.


Step 3 — Run the Migration

Create the activity log table.

php artisan migrate

A table called:

activity_log

will be created.


Step 4 — Understanding the Database Table

The table stores information such as:

ColumnDescription
idActivity ID
log_nameLog category
descriptionActivity description
subject_typeModel type
subject_idModel ID
causer_typeUser model
causer_idUser ID
propertiesExtra information
created_atTimestamp

Step 5 — Logging a Simple Activity

Suppose a user creates a product.

use Spatie\Activitylog\activity;

activity()
    ->log('Product created');

This creates a new activity entry.


Step 6 — Add a Log Name

Organize logs by category.

activity('products')
    ->log('Product created');

Now the log belongs to the products category.


Step 7 — Log the Authenticated User

When a logged-in user performs an action:

activity()
    ->causedBy(auth()->user())
    ->log('Updated profile');

The package records:


Step 8 — Attach a Subject

You can associate an activity with a model.

activity()
    ->performedOn($product)
    ->log('Product updated');

Now the log is linked to the product.


Step 9 — Add Extra Properties

Store additional information.

activity()
    ->withProperties([
        'price' => 500,
        'category' => 'Electronics'
    ])
    ->log('Product created');

These values are stored as JSON.


Step 10 — Log Model Changes Automatically

Instead of manually logging every action, you can let the package do it automatically.

Example Product model:

namespace App\Models;

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

class Product extends Model
{
    use LogsActivity;

    protected $fillable = [
        'name',
        'price',
        'stock'
    ];

    public function getActivitylogOptions(): LogOptions
    {
        return LogOptions::defaults()
            ->logOnly([
                'name',
                'price',
                'stock'
            ]);
    }
}

Now Laravel automatically logs:


Step 11 — Log Only Dirty Attributes

Sometimes you only want to record fields that actually changed.

public function getActivitylogOptions(): LogOptions
{
    return LogOptions::defaults()
        ->logOnly([
            'name',
            'price'
        ])
        ->logOnlyDirty();
}

Example:

Old value:

Price = 500

New value:

Price = 700

Only the changed field is logged.


Step 12 — Skip Empty Logs

Prevent logs when nothing has changed.

public function getActivitylogOptions(): LogOptions
{
    return LogOptions::defaults()
        ->logOnlyDirty()
        ->dontSubmitEmptyLogs();
}

Step 13 — Customize the Description

Provide meaningful descriptions.

public function getActivitylogOptions(): LogOptions
{
    return LogOptions::defaults()
        ->setDescriptionForEvent(
            fn(string $eventName) => "Product has been {$eventName}"
        );
}

Possible results:

Product has been created

Product has been updated

Product has been deleted

Step 14 — Retrieve Activity Logs

Fetch all logs.

use Spatie\Activitylog\Models\Activity;

$activities = Activity::latest()->get();

Step 15 — Display Activity Logs

Example Blade view:

@foreach($activities as $activity)

{{ $activity->description }}

{{ $activity->created_at }}

@endforeach

Step 16 — Get Logs for a Specific Model

Retrieve logs related to a particular product.

$product->activities;

Step 17 — Get the User Who Performed the Action

$activity->causer;

Example:

John Doe

Step 18 — Access the Subject

Retrieve the related model.

$activity->subject;

Example:

Product #25

Step 19 — Read Extra Properties

$activity->properties;

Retrieve a specific value.

$activity->properties['price'];

Step 20 — Delete Old Logs

You can remove old logs manually.

Activity::where('created_at', '<', now()->subMonths(6))
    ->delete();

Or schedule a cleanup using Laravel’s task scheduler if your application generates many logs.


Example Controller

public function store(Request $request)
{
    $product = Product::create([
        'name' => $request->name,
        'price' => $request->price,
        'stock' => $request->stock,
    ]);

    activity('products')
        ->performedOn($product)
        ->causedBy(auth()->user())
        ->withProperties([
            'price' => $product->price
        ])
        ->log('Product created');

    return back();
}

Best Practices


Common Errors

Table not found

Run:

php artisan migrate

Nothing is logged

Check that:

Changes are not recorded

Ensure:


Summary

You learned how to:

With these fundamentals, you can build an effective audit trail that helps monitor user actions and data changes in your Laravel applications.

Exit mobile version