Cara Mudah Membuat Activity Log Pada Laravel

1. Menambahkan Depedency

Di sini kita perlu menginstall depedency dengan menjalankan perintah.

$ composer require spatie/laravel-activitylog
$ php artisan vendor:publish --provider="Spatie\Activitylog\ActivitylogServiceProvider" --tag="migrations"
$ php artisan migrate
$ php artisan vendor:publish --provider="Spatie\Activitylog\ActivitylogServiceProvider" --tag="config"

2. Menambahkan LogsActivity Pada Model

use Spatie\Activitylog\Traits\LogsActivity;
use Spatie\Activitylog\Models\Activity;

class Announcement extends Model
{
    use HasFactory, LogsActivity;
    
    protected static $recordEvents = ['created', 'updated'];
    
    protected static $ignoreChangedAttributes = ['updated_at'];
    
    protected static $logFillable = true;
    
    protected static $logOnlyDirty = true;
    
    public static $logName = 'announcement';
    
    public function getDescriptionForEvent(string $eventName): string
    {
        if ($eventName == "created") {
            return Auth::user()->name . " created for announcement";
        } elseif ($eventName == "updated") {
            return Auth::user()->name . " updated for announcement";
        }
        
        return "You have {$eventName} announcement";
    }
    
    public function tapActivity(Activity $activity)
    {
        if (!empty(request()->note)) {
            $activity->properties = $activity->properties->merge([
                'note' => request()->note,
            ]);
        }
    }
}

note : pada getDescriptionForEvent merupakan custom pada description berdasarkan event nya, tapActivity merupakan kebutuhan jika ada tambahan pada properties.

2. Menampilkan Activity Pada Controller

use Spatie\Activitylog\Models\Activity;

    public function edit(Announcement $announcement)
    {
        $activities = Activity::forSubject($announcement)->get();
        
        //
    }

Sekian untuk kali ini semoga bermanfaat :D untuk lebih lanjut bisa kunjungi link tersebut.