Laravel Observer Pattern Skill
Use this skill when you need to trigger logic based on Eloquent Model events (created, updated, deleted, etc.).
When to use
-
Sending emails after user registration.
-
Logging changes for audit entry.
-
Updating summary tables.
Rules
- Silent Handling
-
Observers should handle exceptions gracefully or let them bubble up depending on criticality.
-
Avoid putting slow blocking logic (like API calls) directly in Observer. Dispatch a Job/Event instead.
- Registration
-
Ensure the Observer is registered in the model attribute #[ObservedBy(UserObserver::class)] (Laravel 10+ standard) or in AppServiceProvider .
-
Prefer Attributes:
#[ObservedBy(UserObserver::class)] class User extends Authenticatable { // ... }
- Methods
- Type hint the model in the observer methods.
public function created(User $user): void { // ... }