Audit Trail
Who changed what, when and from where: every Eloquent create, update and delete, plus explicit events, written to magic_starter_audits.
On this page
Quick Reference#
// config/magic-starter.php
'features' => [
Features::audit(),
],
| Item | Value |
|---|---|
| Install | php artisan magic-starter:install --features=audit, then php artisan migrate. |
| Table | magic_starter_audits. |
| Retention | magic-starter.audit.retention_days, 365 by default and never less than one day. |
| Prune | php artisan magic-starter:audit:prune, scheduled daily while the feature is on. |
| Skip a model | List it in audit.exclude, or wrap the write in Auditor::withoutAuditing(). |
| Record a bulk write | Run the write, then call Auditor::record($event, $subject, $context) yourself. |
Introduction#
The audit trail answers who changed what, when, and from where. With the feature on, every Eloquent create, update and delete in the application is written to magic_starter_audits, together with the acting user and the request it came from. Writes made through the admin panel are recorded as one admin.* row each.
Enabling#
Audit is opt-in:
// config/magic-starter.php
'features' => [
Features::audit(),
],
Run php artisan magic-starter:install --features=audit to publish the migration, then php artisan migrate. While the feature is off, no listener is registered and model events cost nothing extra.
What Is Recorded#
| Column | Content |
|---|---|
event |
created, updated, deleted, or an explicit name such as admin.user.updated |
auditable_type, auditable_id |
The record the event is about |
actor_type, actor_id |
The authenticated user, when there is one |
related_user_id |
The user the row concerns: the subject itself for a user, otherwise its user_id |
old_values, new_values |
For an update, only the changed keys, with the raw values they held before |
context |
ip, user_agent, url (without its query string) and route |
Key columns are strings, so one column holds integer and UUID keys alike. A row is inserted after the surrounding transaction commits; a change that rolls back leaves no row.
Excluding Models#
'audit' => [
'exclude' => [
\Laravel\Sanctum\PersonalAccessToken::class,
\App\Models\PageView::class,
],
],
exclude lists model classes, subclasses included. The default holds Sanctum's PersonalAccessToken, which stamps last_used_at on every authenticated request and would otherwise write a row per API call; keep it when you add your own. The package always skips its own Audit model, every pivot and the team membership model.
Ignoring Attributes#
A column that moves on every tick, such as last_checked_at, would write a row per tick. Name it as ignored and an update that changes nothing else is not recorded:
// config/magic-starter.php
'audit' => [
'ignore' => [
\App\Models\Monitor::class => ['last_checked_at', 'last_status'],
],
],
class Monitor extends Model
{
protected array $auditIgnore = ['last_checked_at', 'last_status'];
}
ignore maps a model class (subclasses included) to its attributes, and the model's own $auditIgnore adds to that list. An update whose changes are all ignored, apart from updated_at, writes no row. A mixed update is recorded without the ignored keys. A model with no ignore list is audited in full, so even a bare touch() on it writes a row; on a model with one, a touch() that moved no ignored attribute is recorded too. Credential columns (password, remember_token, two_factor_secret, two_factor_recovery_codes, token, device_id) cannot be ignored: a change to one is always recorded, redacted.
Redaction#
A sensitive value is stored as [redacted]; the key stays, so a reader can see that the field changed. A value is redacted when:
- the model lists it in
$hidden; - it is cast
encrypted,encrypted:array(and the other encrypted casts) orhashed; - the model names it in its own
$auditExcludeproperty; - it is
password,remember_token,two_factor_secret,two_factor_recovery_codes,tokenordevice_id(a guest'sdevice_idsigns that guest in throughPOST auth/guest, so it is a credential); - it is listed in
audit.redact.
// config/magic-starter.php
'audit' => [
'redact' => ['api_key'],
],
class Invoice extends Model
{
protected array $auditExclude = ['internal_note'];
}
audit.redact extends the built-in list and can never shorten it, so a published config cannot start storing a password. Old values are stored raw, as the database held them, so an encrypted column appears as ciphertext, never as plaintext.
Recording an Event#
For something that is not a model change, such as an impersonation or an export:
use AnilcanCakir\MagicStarter\Audit\Auditor;
Auditor::record('admin.user_impersonated', $user, [
'reason' => 'support ticket 4411',
]);
The signature is record(string $event, ?Model $subject, array $context = [], ?Authenticatable $actor = null). The actor defaults to the authenticated user, and $context is merged over the request context. It writes nothing while the feature is off.
Newsletter events#
With newsletter-subscription on, consent changes are recorded under explicit event names on the subscriber row:
| Event | When | Context |
|---|---|---|
newsletter.subscribed |
A user consents, from the profile toggle or at registration | consent_version, source |
newsletter.unsubscribed |
A subscription is withdrawn; nothing is written when it already was | via: profile, one_click (the public link) or staff |
admin.newsletter.subscriber_deactivated |
Staff run "Deactivate" in the admin panel | the admin action row, beside the newsletter.unsubscribed row |
The one-click POST carries the token in its URL, so that row's url is stored as null: no audit row ever holds an unsubscribe token. The token is also in the model's $hidden, so a row that records the subscriber stores it as [redacted].
Silencing the Listener#
Auditor::withoutAuditing(function () use ($team): void {
$team->update(['name' => 'Renamed by a migration script']);
});
Only the model listener is silenced, and nested calls are safe. An explicit Auditor::record() inside the callback is still written: suppress the noise, then record the one event that matters.
Reading the Trail#
Add the HasAudits trait to a model to get an audits() relation:
use AnilcanCakir\MagicStarter\Audit\HasAudits;
class Team extends Model
{
use HasAudits;
}
Recording never depends on the trait; it only adds the read side. With the admin panel installed, the Audits resource and a tab on Users and Teams show the same rows.
Pruning#
php artisan magic-starter:audit:prune
Deletes rows older than magic-starter.audit.retention_days (365 by default, and never less than one day), in chunks of 1000. While the feature is on, the package schedules it daily with withoutOverlapping(); your application's scheduler has to be running.
Deleting a User#
A deleted account's trail is personal data and goes with it. Deleting the user model records no row of its own. Once the transaction commits, Auditor::forgetUser() runs:
- every row whose subject is that user is deleted;
- every row whose
related_user_idis that user (their teams, linked accounts) is deleted; - every row where they were the actor stays, with
actor_idset to null,actor_typekept, andipanduser_agentremoved fromcontext: what happened to somebody else's record remains, who did it does not.
A deletion that rolls back erases nothing.
The purge finds rows by user key only. A row keyed by an email address elsewhere is not covered: a team invitation (its values hold the invited address and it relates to the team, not to a user) keeps its audit rows. Delete those yourself when your obligations require it.
A newsletter subscription is covered, but not by the purge: DeleteUser deletes the user's subscriber row (found by user_id, or by address for a row nobody has claimed yet) together with that row's audit rows, inside the deletion's transaction.
What Is Not Captured#
- Query-builder bulk writes (
Model::query()->update(),->delete(),DB::table()), which fire no model events. - Pivot and team membership rows.
- Writes made with model events muted, such as
saveQuietly(). - Models in
audit.exclude, and anything insideAuditor::withoutAuditing().
When such a write matters, make it, then record it with a call to Auditor::record().
Gotchas#
| Mistake | Fix |
|---|---|
Expecting a bulk update() or delete() to be audited |
The query builder fires no model events. Make the write, then record it with a call to Auditor::record(). |
Expecting saveQuietly() to leave a row |
It mutes the events the listener reads. |
| Counting on a rolled-back change appearing in the trail | A row is inserted after the transaction commits, so a rollback leaves none. |
| Relying on the trail after deleting a user | Rows about that user are deleted with the account; rows where they acted keep actor_id as null. |
| Expecting the purge to find rows keyed by an email address | It finds rows by user key only, so a team invitation keeps its rows. Delete those yourself if you must. |
| Expecting old rows to leave without a running scheduler | The package schedules the prune daily, but your application's scheduler has to be running for it to fire. |
Related Documentation#
- Admin Panel: the
admin.*rows and the resource that reads the trail. - Account Deletion: the purge that triggers
Auditor::forgetUser(). - Configuration:
schedule.audit_prune.