Discover how to automate your app's reactions to data changes without messy code!
Why Model events and observers in Laravel? - Purpose & Use Cases
Start learning this pattern below
Jump into concepts and practice - no test required
Imagine you have a website where users can register, update profiles, and delete accounts. You want to send a welcome email, log changes, and clean up related data every time these actions happen.
Manually adding email sending, logging, and cleanup code inside every controller or model method quickly becomes messy and repetitive. It's easy to forget to add some logic, causing bugs and inconsistent behavior.
Laravel's model events and observers let you centralize this logic. You write code once in observer classes that automatically run when models are created, updated, or deleted, keeping your app clean and reliable.
UserController.php:\npublic function update(Request $request, $id) {\n $user = User::find($id);\n $user->update($request->all());\n Mail::sendWelcome($user);\n Log::info('User updated');\n}UserObserver.php:\npublic function updated(User $user) {\n Mail::sendWelcome($user);\n Log::info('User updated');\n}\n// Registered in AppServiceProviderThis lets you keep your code organized and automatically react to model changes without repeating yourself.
When a new order is placed, an observer can automatically update inventory, send confirmation emails, and log the sale without cluttering your order controller.
Manual event handling scatters code and causes mistakes.
Observers centralize reactions to model changes.
Cleaner, easier to maintain, and more reliable applications.
Practice
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]
- Confusing events with database migrations
- Thinking events define relationships
- Assuming events run SQL queries directly
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]
- Using wrong method names like registerObserver
- Passing observer as string instead of ::class
- Confusing attachObserver with observe
public function created(User $user) {
Log::info('User created: ' . $user->id);
}What happens when a new User model is saved?
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]
- Thinking created() deletes the model
- Assuming created() does nothing
- Confusing created() with invalid method
public function boot() {
User::observe();
}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]
- Calling observe() without arguments
- Renaming boot() incorrectly
- Calling observe() on wrong class
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]
- Using created() or deleted() for updates
- Using wasChanged() inside saving() which runs before update
- Checking isDirty() in deleted() event
