Bird
Raised Fist0
Laravelframework~20 mins

Model events and observers in Laravel - Practice Problems & Coding Challenges

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Challenge - 5 Problems
🎖️
Model Events Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What happens when a model observer's creating method returns false?
In Laravel, if an observer's creating method returns false, what is the effect on the model save operation?
AThe model save operation is cancelled and the model is not saved to the database.
BThe model save operation is delayed until the observer returns <code>true</code>.
CAn exception is thrown and the application crashes.
DThe model save operation continues normally and the model is saved.
Attempts:
2 left
💡 Hint
Think about how returning false in event handlers affects the flow.
📝 Syntax
intermediate
2:00remaining
Which code correctly registers a model observer in Laravel?
Given a model Post and an observer PostObserver, which code snippet correctly registers the observer?
AObserver::register(Post::class, PostObserver::class);
BPostObserver::observe(Post::class);
CPost::registerObserver(PostObserver::class);
DPost::observe(PostObserver::class);
Attempts:
2 left
💡 Hint
Remember the static method used on the model to attach observers.
❓ state_output
advanced
2:00remaining
What is the output after saving a model with an observer modifying an attribute?
Consider this observer method:
public function saving(Post $post) {
    $post->title = strtoupper($post->title);
}

What will be the title value in the database after saving a Post with title hello world?
A"HELLO WORLD"
B"hello world"
Cnull
DAn error occurs because <code>title</code> is modified in the observer.
Attempts:
2 left
💡 Hint
The saving event happens before the model is saved.
🔧 Debug
advanced
2:00remaining
Why does the observer method not trigger on model update?
You have this observer method:
public function updated(Post $post) {
    Log::info('Post updated');
}

But when you update a Post model, the log never appears. What is the most likely cause?
AThe model is updated using <code>update()</code> method which does not fire events.
BThe <code>updated</code> method name is misspelled.
CThe observer was not registered with the model.
DThe <code>updated</code> event only fires on creation, not updates.
Attempts:
2 left
💡 Hint
Check if the observer is properly connected to the model.
🧠 Conceptual
expert
2:00remaining
Which model event is triggered after a model is deleted and the database transaction is committed?
In Laravel, which model event fires only after the model is deleted and the database transaction is fully committed?
Adeleting
BforceDeleted
Cdeleted
DdeletedCommitted
Attempts:
2 left
💡 Hint
Think about events related to force deleting and transaction commits.

Practice

(1/5)
1. What is the main purpose of model events in Laravel?
easy
A. To react automatically when a model is created, updated, or deleted
B. To define database table relationships
C. To create database migrations
D. To write raw SQL queries

Solution

  1. Step 1: Understand model events

    Model events are hooks that trigger when a model changes, like creation or deletion.
  2. Step 2: Identify their purpose

    They let you run code automatically on these changes, such as logging or notifications.
  3. Final Answer:

    To react automatically when a model is created, updated, or deleted -> Option A
  4. Quick 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
A. User::addObserver('UserObserver');
B. User::observe(UserObserver::class);
C. User::registerObserver(UserObserver);
D. User::attachObserver(UserObserver::class);

Solution

  1. Step 1: Recall observer registration syntax

    Laravel uses the static method observe() on the model to register observers.
  2. Step 2: Match correct syntax

    The correct syntax is Model::observe(ObserverClass::class); which matches User::observe(UserObserver::class);.
  3. Final Answer:

    User::observe(UserObserver::class); -> Option B
  4. Quick 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:
public function created(User $user) {
    Log::info('User created: ' . $user->id);
}

What happens when a new User model is saved?
medium
A. An error is thrown because created() is invalid
B. The user is deleted immediately
C. Nothing happens automatically
D. A log entry with the new user's ID is created

Solution

  1. Step 1: Understand the created() observer method

    The created() method runs after a model is saved for the first time.
  2. Step 2: Analyze the method body

    It logs info with the new user's ID, so a log entry is made.
  3. Final Answer:

    A log entry with the new user's ID is created -> Option D
  4. Quick 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
A. The observe() method is called without passing the observer class
B. The boot() method should be named bootObserver()
C. User model cannot have observers
D. The observe() method should be called on the observer class

Solution

  1. Step 1: Check observe() method usage

    observe() requires the observer class as an argument to register it.
  2. Step 2: Identify missing argument

    Here, observe() is called with no arguments, so it will cause an error.
  3. Final Answer:

    The observe() method is called without passing the observer class -> Option A
  4. Quick 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
A. Use the deleted(Post $post) method and check if $post->isDirty('title') is true
B. Use the saving(Post $post) method and check if $post->wasChanged('title') is true
C. Use the updated(Post $post) method and check if $post->wasChanged('title') is true
D. Use the created(Post $post) method and check if $post->title is not empty

Solution

  1. Step 1: Identify correct event for update

    The updated() method runs after a model is updated, suitable for this task.
  2. Step 2: Check how to detect changed attributes

    wasChanged('title') returns true if the title attribute was changed during the update.
  3. Step 3: Combine logic

    Inside updated(), check wasChanged('title') to log only when title changed.
  4. Final Answer:

    Use the updated(Post $post) method and check if $post->wasChanged('title') is true -> Option C
  5. Quick 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