Skip to content

Instantly share code, notes, and snippets.

@aytacmalkoc
Last active August 4, 2024 12:54
Show Gist options
  • Save aytacmalkoc/2ec63805d6311ddd2228e7d6cd42104b to your computer and use it in GitHub Desktop.
Save aytacmalkoc/2ec63805d6311ddd2228e7d6cd42104b to your computer and use it in GitHub Desktop.
Laravel HasCrudLogs trait for logging model actions.
<?php
namespace App\Traits;
use Illuminate\Support\Facades\Log;
trait HasCrudLogs
{
public static function bootHasCrudLogs(): void
{
static::created(function ($model) {
self::logAction('created', $model);
});
static::updated(function ($model) {
self::logAction('updated', $model);
});
static::deleted(function ($model) {
self::logAction('deleted', $model, true);
});
static::replicating(function ($model) {
self::logAction('replicating', $model);
});
}
protected static function logAction($action, $model, $isDeleted = false): void
{
$userId = auth()->id() ?? 'guest';
$className = get_class($model);
$modelId = $model->getKey();
$logLevel = self::logType($action);
if ($action === 'updated') {
$original = $model->getOriginal();
$changes = $model->getDirty();
Log::channel('hub')->$logLevel("User {$userId} has {$action} a {$className} with ID {$modelId}", [
'original' => $original,
'changes' => $changes
]);
} elseif ($isDeleted) {
$changes = $model->getAttributes();
Log::channel('hub')->$logLevel("User {$userId} has {$action} a {$className} with ID {$modelId}", [
'attributes' => $changes
]);
} else {
$changes = $model->getDirty();
Log::channel('hub')->$logLevel("User {$userId} has {$action} a {$className} with ID {$modelId}", [
'changes' => $changes
]);
}
}
protected static function logType(string $action): string
{
return match ($action) {
'creating', 'created' => 'info',
'updating', 'updated' => 'notice',
'deleting', 'deleted' => 'warning',
default => 'debug',
};
}
}
@aytacmalkoc
Copy link
Author

Example:

<?php

namespace App\Models;

use App\Traits\HasCrudLogs;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Post extends Model
{
    use HasFactory, SoftDeletes, HasCrudLogs;
}
[2024-08-04 05:39:11] local.NOTICE: User 1 is updated a App\Models\Category with ID 16 {"changes":{"name":"Test Category","slug":"test-category","updated_at":"2024-08-04 05:39:11"}} 

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment