Last active
August 4, 2024 12:54
-
-
Save aytacmalkoc/2ec63805d6311ddd2228e7d6cd42104b to your computer and use it in GitHub Desktop.
Laravel HasCrudLogs trait for logging model actions.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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', | |
}; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example: