Model events let you run code automatically when something happens to your data. Observers help organize this code neatly.
Model events and observers in Laravel
Start learning this pattern below
Jump into concepts and practice - no test required
or
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
Syntax
Laravel
php // Creating an observer class class UserObserver { public function created(User $user) { // code to run after a user is created } public function updated(User $user) { // code to run after a user is updated } } // Registering the observer in a service provider User::observe(UserObserver::class);
Observer methods match model events like created, updated, deleted.
Register observers usually in AppServiceProvider or a dedicated provider.
Examples
Laravel
php class PostObserver { public function deleting(Post $post) { // Remove related comments before deleting a post $post->comments()->delete(); } } Post::observe(PostObserver::class);
Laravel
php class OrderObserver { public function created(Order $order) { // Send notification when order is created Notification::send($order->user, new OrderPlaced($order)); } } Order::observe(OrderObserver::class);
Sample Program
This example shows a User model and a UserObserver that logs a message when a user is created. The observer is registered in the AppServiceProvider.
Laravel
<?php namespace App\Models; use Illuminate\Database\Eloquent\Model; class User extends Model { // User model code } namespace App\Observers; use App\Models\User; use Illuminate\Support\Facades\Log; class UserObserver { public function created(User $user) { Log::info("User created: {$user->email}"); } } namespace App\Providers; use Illuminate\Support\ServiceProvider; use App\Models\User; use App\Observers\UserObserver; class AppServiceProvider extends ServiceProvider { public function boot() { User::observe(UserObserver::class); } } // When a new user is created, a log entry is made automatically.
Important Notes
Model events include: creating, created, updating, updated, deleting, deleted, saving, saved, restoring, restored.
Observers keep your code clean by separating event logic from models.
Remember to register observers to activate them.
Summary
Model events let you run code when data changes.
Observers organize event code in separate classes.
Register observers to connect them with models.
Practice
1. What is the main purpose of model events in Laravel?
easy
Solution
Step 1: Understand model events
Model events are hooks that trigger when a model changes, like creation or deletion.Step 2: Identify their purpose
They let you run code automatically on these changes, such as logging or notifications.Final Answer:
To react automatically when a model is created, updated, or deleted -> Option AQuick Check:
Model events = react on model changes [OK]
Hint: Model events trigger on data changes automatically [OK]
Common Mistakes:
- Confusing events with database migrations
- Thinking events define relationships
- Assuming events run SQL queries directly
2. Which of the following is the correct way to register an observer for a model in Laravel?
easy
Solution
Step 1: Recall observer registration syntax
Laravel uses the static method observe() on the model to register observers.Step 2: Match correct syntax
The correct syntax is Model::observe(ObserverClass::class); which matches User::observe(UserObserver::class);.Final Answer:
User::observe(UserObserver::class); -> Option BQuick Check:
Register observer = observe() method [OK]
Hint: Use observe() method with ::class for observers [OK]
Common Mistakes:
- Using wrong method names like registerObserver
- Passing observer as string instead of ::class
- Confusing attachObserver with observe
3. Given this observer method in Laravel:
What happens when a new User model is saved?
public function created(User $user) {
Log::info('User created: ' . $user->id);
}What happens when a new User model is saved?
medium
Solution
Step 1: Understand the created() observer method
The created() method runs after a model is saved for the first time.Step 2: Analyze the method body
It logs info with the new user's ID, so a log entry is made.Final Answer:
A log entry with the new user's ID is created -> Option DQuick Check:
created() logs user ID after save [OK]
Hint: created() runs after first save, logs info [OK]
Common Mistakes:
- Thinking created() deletes the model
- Assuming created() does nothing
- Confusing created() with invalid method
4. What is wrong with this observer registration code?
public function boot() {
User::observe();
}medium
Solution
Step 1: Check observe() method usage
observe() requires the observer class as an argument to register it.Step 2: Identify missing argument
Here, observe() is called with no arguments, so it will cause an error.Final Answer:
The observe() method is called without passing the observer class -> Option AQuick Check:
observe() needs observer class argument [OK]
Hint: Always pass observer class to observe() [OK]
Common Mistakes:
- Calling observe() without arguments
- Renaming boot() incorrectly
- Calling observe() on wrong class
5. You want to log a message every time a Post model is updated, but only if the title has changed. How should you implement this in a PostObserver?
hard
Solution
Step 1: Identify correct event for update
The updated() method runs after a model is updated, suitable for this task.Step 2: Check how to detect changed attributes
wasChanged('title') returns true if the title attribute was changed during the update.Step 3: Combine logic
Inside updated(), check wasChanged('title') to log only when title changed.Final Answer:
Use the updated(Post $post) method and check if $post->wasChanged('title') is true -> Option CQuick Check:
updated() + wasChanged('title') detects title changes [OK]
Hint: Use updated() and wasChanged() to detect attribute changes [OK]
Common Mistakes:
- Using created() or deleted() for updates
- Using wasChanged() inside saving() which runs before update
- Checking isDirty() in deleted() event
