Model Observers: Audit Changes Without Messy Controllers
Track model changes using observers so audit logic stays centralized and consistent.
Christopher Evans
November 7, 2025
1.8k53
Observers let you react to model events like created, updated, deleted.
This helps for:
- audit logs
- cache invalidation
- notifications
## Create an observer
```bash
php artisan make:observer PostObserver --model=Post
```
## Example: log updates
```php
public function updated(Post $post): void {
AuditLog::create([
'entity' => 'post',
'entity_id' => $post->id,
'action' => 'updated',
'user_id' => auth()->id(),
]);
}
```
## Register observer
```php
Post::observe(PostObserver::class);
```
## Flow
```mermaid
flowchart LR
A[Post Updated] --> B[Observer Triggered]
B --> C[Audit Log Saved]
```
In the next tutorial, we will implement request validation + DTO patterns for cleaner services.
#Laravel#Architecture#Advanced