Eloquent Events & Observers
Eloquent fires events during model lifecycle — creating, created, updating, updated, deleting, deleted. Observers centralize event listeners for a model. Use them for auto-generating slugs, clearing caches, logging changes, or sending notifications.
Model Events & Observers
// php artisan make:observer PostObserver --model=Post
class PostObserver
{
public function creating(Post $post): void
{
// Auto-generate slug before saving
$post->slug = Str::slug($post->title);
}
public function created(Post $post): void
{
// Send notification after post is created
$post->user->notify(new PostPublished($post));
}
public function updating(Post $post): void
{
// Update slug if title changed
if ($post->isDirty('title')) {
$post->slug = Str::slug($post->title);
}
}
public function deleted(Post $post): void
{
// Clean up related files
Storage::delete($post->image_path);
}
}
// Register in AppServiceProvider:
Post::observe(PostObserver::class);Module 5 Review
Tip
Tip
Practice Eloquent Events Observers in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Define the relationship, Eloquent builds the SQL automatically
Practice Task
Note
Practice Task — (1) Write a working example of Eloquent Events Observers from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Common Mistake
Warning
A common mistake with Eloquent Events Observers is skipping edge case testing — empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready laravel code.