0
0
Laravelframework~10 mins

Model events and observers in Laravel - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Model events and observers
Model Action Triggered
Check for Registered Observer
Yes
Call Observer Method
Execute Custom Logic
Continue Model Process
End
When a model action happens, Laravel checks if an observer is registered. If yes, it calls the observer method to run custom code before continuing.
Execution Sample
Laravel
use IlluminateSupportStr;

class UserObserver {
  public function creating(User $user) {
    $user->api_token = Str::random(60);
  }
}

User::observe(UserObserver::class);

User::create(['name' => 'Anna']);
This code sets an API token automatically when a new User is created using an observer.
Execution Table
StepEvent TriggeredObserver Method CalledAction TakenModel State
1User::create() calledNoStart creating userUser instance with name='Anna', api_token=null
2creating eventcreating()Set api_token to random stringUser instance with name='Anna', api_token='random60chars'
3created eventNoUser saved to databaseUser saved with name='Anna', api_token='random60chars'
4EndNoCreation completeUser record exists with api_token
💡 User creation finishes after observer sets api_token during creating event
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3Final
user->namenullAnnaAnnaAnnaAnna
user->api_tokennullnullrandom60charsrandom60charsrandom60chars
Key Moments - 2 Insights
Why does the api_token get set before the user is saved?
Because the observer's creating() method runs during the 'creating' event, which happens before the model is saved, as shown in execution_table step 2.
What happens if no observer is registered?
The model events still fire, but no custom code runs. The execution_table shows 'No' under Observer Method Called when no observer is registered.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 2. What change happens to the user model?
Aapi_token is set to a random string
BUser name is changed to null
CUser is saved to database
DNo changes happen
💡 Hint
Check the 'Action Taken' and 'Model State' columns at step 2 in execution_table
At which step does the user get saved to the database?
AStep 1
BStep 2
CStep 3
DStep 4
💡 Hint
Look for 'User saved to database' in the 'Action Taken' column in execution_table
If the observer's creating() method was removed, what would happen to api_token?
AIt would still be set automatically
BIt would remain null
CUser creation would fail
Dapi_token would be set after saving
💡 Hint
Refer to variable_tracker and execution_table steps where observer sets api_token
Concept Snapshot
Model events fire during model actions like creating or updating.
Observers listen to these events and run custom code.
Register observers with Model::observe(ObserverClass::class).
Observer methods run before or after model actions.
Use observers to keep model logic clean and reusable.
Full Transcript
In Laravel, model events happen during actions like creating or updating a model. Observers are classes that listen to these events and run custom code. For example, when creating a User, the creating event fires before saving. If an observer is registered, its creating() method runs and can modify the model, like setting an api_token. After that, the model saves with the updated data. This process helps keep code organized by separating event logic from controllers or models. The execution table shows each step: starting creation, observer setting api_token, saving the user, and finishing. Variables like user->api_token change during the observer method. If no observer is registered, the model still saves but without custom changes. Observers are registered using User::observe(UserObserver::class). This pattern helps automate tasks during model lifecycle events.