Using Traits implement Activity Log in Laravel
Laravel Tip: Add Activity Logs to Any Model with a Simple Trait
Instead of repeating “who updated what” code in every model, push it into a Trait. Then enable logging by dropping that Trait onto a model — done!
1. Create the Migration
php artisan make:migration create_activity_logs_table
Schema::create('activity_logs', function (Blueprint $table) {
$table->id();
$table->string('model');
$table->unsignedBigInteger('model_id');
$table->string('action');
$table->json('changes')->nullable();
$table->unsignedBigInteger('user_id')->nullable();
$table->timestamps();
});
2. Make the Trait
namespace App\Traits;
use App\Models\ActivityLog;
trait LogsActivity
{
public static function bootLogsActivity(): void
{
static::created(function ($model) {
$model->writeActivity('created', $model->getAttributes());
});
static::updated(function ($model) {
$model->writeActivity('updated', $model->getChanges());
});
static::deleted(function ($model) {
$model->writeActivity('deleted');
});
}
protected function writeActivity(string $action, array $changes = []): void
{
ActivityLog::create([
'model' => static::class,
'model_id' => $this->getKey(),
'action' => $action,
'changes' => json_encode($changes),
'user_id' => auth()->id(),
]);
}
}
3. Apply to Any Model
use App\Traits\LogsActivity;
class Post extends Model
{
use LogsActivity;
protected $fillable = ['title', 'content'];
}
Every create, update, or delete on Post now leaves a record in activity_logs.
Drop the same Trait on User, Order, or any model — no extra wiring.
Why This Rocks
- Zero copy-paste across models
- Centralized, testable logging logic
- Perfect foundation for an “Audit Trail” UI