CRUD Activity Logs With Example In Laravel 6

Activity logs in laravel

In this tutorial, i will show you how to add activity logs in laravel 6 web application. In multi-user/admin web application, its almost require to add user activity logs to track user activity. Activities like create, read, update and delete some data by some user.

Today i will show you how to add activity logs in laravel using spatie/laravel-activitylog package. In this tutorial we will use add activity logs in Task CRUD by user.

So without loosing extra time lets start to implement activity logs in laravel step by step.

Setup Fresh Laravel Project

We have already created todo crud tutorial in laravel 6. I will use it and add activity logs in it. So if you haven’t read it then please check it first and come back here. You have to follow all the instructions mentioned in the tutorial.

Related:  Larave 6 - CRUD Tutorial With Authentication For Beginners

Activity Log Package Installation & Configuration

Now lets install spatie/laravel-activitylog package using below command.

composer require spatie/laravel-activitylog

composer require spatie/laravel-activitylog

The package will automatically register itself.

Now publish migrations using below command.

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

Note: The default migration assumes you are using integers for your model IDs. If you are using UUIDs, or some other format, adjust the format of the subject_id and causer_id fields in the published migration before continuing.

Next, run php artisan migrate command to create activity_log table.

If you require to change in package configuration then you can publish package configuration by below artisan command.

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

Above command will create activitylog.php file under config/ directory.

Change configuration as your requirement. If you dont want to change configuration the leave it as it is.

Okay, spatie laravel-activitylog package installation successfully done. 🙂

Spatie laravel-activitylog package provide two methods to define activity logs.

  1. Add activity logs in controller methods
  2. Define activity logs in model to log model events

# Add Activity Logs In Controller

Open TodoController.php file and add create todo activity logs in store method. Its very simple. See below example.

TodoController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Todo;
use Auth;

class TodoController extends Controller
{
    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $user = Auth::user();
        $input = $request->input();
        $input['user_id'] = $user->id;
        $todoStatus = Todo::create($input);
        if ($todoStatus) {

            // Add activity logs
            activity('todo')
                ->performedOn($todoStatus)
                ->causedBy($user)
                //->withProperties(['customProperty' => 'customValue'])
                ->log('Todo created by ' . $user->name);

            $request->session()->flash('success', 'Todo successfully added');
        } else {
            $request->session()->flash('error', 'Oops something went wrong, Todo not saved');
        }
        return redirect('todo');
    }
}

In above store method, we are storing activity logs after todo successfully created. Lets understand about activity log code.

  • activity() :  We can pass log name in activity() helper function, if we won’t then it use default log name specified in config/activitylog.php file.
  • performedOn() performedOn() function accept model as a parameter on which this action happen. In our case we have passed todo model.
  • causedBy() causedBy() function accept model as a parameter by which this action done. In our case we passed user model as user created todo task.
  • withProperties() withProperties() function store extra custom properties in DB. It stores old values and new values of that custom property. In our case we are not using it.
  • log() log() function accepts activity log text.

We can write update todo and delete todo activity logs same way.

Add below code to update() method.

// Update activity logs
activity('todo')
    ->performedOn($todo)
    ->causedBy($user)
    ->log('Todo updated by ' . $user->name);

Also, add below code to delete() method.

// Delete activity logs
activity('todo')
    ->performedOn($todo)
    ->causedBy($user)
    ->log('Todo deleted by ' . $user->name);

Logging Activity Using Placeholder

When logging an activity you may use placeholders that start with :subject:causer or :properties. These placeholders will get replaced with the properties of the given subject, causer or property.

Here’s an example:

activity()
    ->performedOn($article)
    ->causedBy($user)
    ->withProperties(['laravel' => 'awesome'])
    ->log('The subject name is :subject.name, the causer name is :causer.name and Laravel is :properties.laravel');

$lastActivity = Activity::all()->last();
$lastActivity->description; //returns 'The subject name is todo name, the causer name is user name and Laravel is awesome';

# Define Activity Logs In Model To Log Model Events

In this method, we don’t need to write activity logs for every event in controller. Instead we need to use Spatie\Activitylog\Traits\LogsActivity  trait in model shown as below. This will log every events made on model such as when a model is created, updated and deleted.

As a bonus the package will also log the changed attributes for all these events when setting $logAttributes property on the model.

Todo.php

<?php

namespace App;

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

class Todo extends Model
{
    use LogsActivity;
    
    // Customize log name
    protected static $logName = 'todo';
    protected $fillable = ['title', 'description', 'user_id', 'status'];
    
    // Only defined attribute will store in log while any change
    protected static $logAttributes = ['title', 'description', 'status'];

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

In $logAttributes property, The attributes that need to be logged can be defined either by their name or you can put in a wildcard '*' to log any attribute that has changed.

Customizing the events being logged

By default the package will log the createdupdateddeleted events. You can modify this behavior by setting the $recordEvents property on a model.

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

Prevent save logs items that have no changed attribute

Setting $submitEmptyLogs to false prevents the package from storing empty logs. Storing empty logs can happen when you only want to log a certain attribute but only another changes.

protected static $submitEmptyLogs = false;

Enable-Disable Logging On Demand

you can disable or enable logging if you don’t want to store log on certain actions. To disable logging you can use activity()->disableLogging(); function in controller before any model action happen. Same way you can enable logging using activity()->enableLogging(); Check below example for more understanding.

$todo = Todo::create([
   'title' => 'Todo name',
   'description' => 'Todo Description'
]);

// Updating with logging disabled
$todo->disableLogging();

$todo->update(['title' => 'Todo name updated.']);

// Deleting with logging enabled
$todo->enableLogging();

$todo->delete();

Retrieving Stored Activity Logs

Finally, we can retrieve stored activity logs using defined log name. The Activity model is just a regular Eloquent model that you know and love:

Activity::where('log_name' , 'todo')->get(); //returns all activity from the 'todo'

You can get more information about this package from its official docs.

Final Words

I hope you enjoyed while performing activity logs in Laravel tutorial. Let me know if you face any query in comment section. Also please share with your friends and support me. Thank you very much 🙂

About Chintan Panchal

I am web developer having 6+ year of experience of web development. Currently working on laravel and have worked on codeigniter, cakephp, symfony. Thank you :)

View all posts by Chintan Panchal →

Leave a Reply

Your email address will not be published.

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