When you’re building something in Laravel, there are often times you want extra things to happen whenever a model changes. For example:
- Send an email when a user signs up
- Write something to the logs
- Update related data
- Send a notification
Of course, you could stick that code directly into your model or controller, but pretty soon it gets messy. That’s where Laravel Observers save the day. They give you one clean place to put all that “when this happens, do that” logic.
What Are Laravel Observers?
Observers are special classes that listen to events on your models. These events include things like:
- creating / created
- updating / updated
- deleting / deleted
You don't need to use all of them, just pick the ones you care about.
Why Use Them?
- Keeps your models clean and focused
- Lets you reuse logic easily across projects
- Puts event-handling code in a single place
Let's dive in to an example:
Let's say you want to send a welcome email every time a new user registers. Perfect use case for an observer!
First, create an observer with below command:
php artisan make:observer UserObserver --model=User
This creates a new file at app/Observers/UserObserver.php.
Laravel won't know about your new observer until you register it. There are two ways:
Option 1. Using the #[ObservedBy]
Attribute
<?php
use App\Observers\UserObserver;
use Illuminate\Database\Eloquent\Attributes\ObservedBy;
#[ObservedBy([UserObserver::class])]
class User extends Authenticatable
{
//
}
Option 2: Register in a Service Provider
<?php
use App\Models\User;
use App\Observers\UserObserver;
public function boot(): void
{
User::observe(UserObserver::class);
}
Now open up app/Observers/UserObserver.php and add the code to send the welcome email:
<?php
namespace App\Observers;
use App\Models\User;
use Illuminate\Support\Facades\Mail;
use App\Mail\WelcomeEmail;
class UserObserver
{
public function created(User $user): void
{
Mail::to($user->email)->send(new WelcomeEmail());
}
}
That's it. Whenever a user is created, Laravel will automatically fire this method and send the email.
If you don't have a WelcomeEmail yet, create one:
php artisan make:mail WelcomeEmail --markdown=emails.welcome
One Last Tip 📝
If you’re just testing and don’t want to set up a real email service yet, you can make Laravel write all emails to the log file instead of actually sending them.
Just update your .env
file like this:
MAIL_MAILER=log
Now, whenever an email is sent, you’ll see it saved inside storage/logs/laravel.log
. That way you can confirm your code is working without worrying about mail servers.
Thank you for reading the article.