php
45 lines · 6 steps
How Eloquent observers hook lifecycle events in Laravel
An OrderObserver runs side effects at each stage of a model's life — creating, created, updated, deleting, and restored.
Explained by
highlit
1<?php
2
3namespace App\Observers;
4
5use App\Models\Order;
6use App\Jobs\GenerateInvoice;
7use App\Notifications\OrderShipped;
8use Illuminate\Support\Str;
9use Illuminate\Support\Facades\Log;
10
11class OrderObserver
12{
13 public function creating(Order $order): void
14 {
15 $order->reference ??= 'ORD-'.Str::upper(Str::random(10));
16 }
17
18 public function created(Order $order): void
19 {
20 GenerateInvoice::dispatch($order)->afterCommit();
21
22 Log::info('Order placed', [
23 'order_id' => $order->id,
24 'total' => $order->total,
25 ]);
26 }
27
28 public function updated(Order $order): void
29 {
30 if ($order->wasChanged('status') && $order->status === 'shipped') {
31 $order->customer->notify(new OrderShipped($order));
32 }
33 }
34
35 public function deleting(Order $order): void
36 {
37 $order->items()->delete();
38 $order->payments()->delete();
39 }
40
41 public function restored(Order $order): void
42 {
43 $order->forceFill(['status' => 'reopened'])->saveQuietly();
44 }
45}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Observers centralize model side effects in named methods that Eloquent fires automatically on each lifecycle event.
- 2Deferring work with afterCommit and saveQuietly avoids dispatching on rolled-back transactions and prevents recursive event loops.
- 3wasChanged lets update logic react only to the specific fields that actually changed.
Related explainers
php
<?php class NameParser {
Parsing a full name into components in PHP
string-parsing
arrays
normalization
Intermediate
8 steps
php
<?php namespace App\Services\Checkout;
Validating coupons with Laravel's Pipeline
pipeline
chain of responsibility
transactions
Intermediate
7 steps
php
<?php namespace App\Services;
How a password strength validator works in PHP
validation
regular-expressions
data-driven
Intermediate
8 steps
php
<?php namespace App\Services;
Building a cached daily leaderboard in Laravel
caching
aggregation
eager-loading
Intermediate
9 steps
php
<?php final class RotatingFileLogger {
How a rotating file logger works in PHP
logging
file-rotation
io
Intermediate
9 steps
php
class TwoFactorController extends Controller { public function show(Request $request): View|RedirectResponse {
Two-factor auth challenge flow in Laravel
authentication
two-factor
middleware
Intermediate
10 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/how-eloquent-observers-hook-lifecycle-events-in-laravel-explained-php-30a8/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.