Courses

Laravel 11 Eloquent: Expert Level

Model Observers and Their Methods

Summary of this lesson:
- Creating and configuring Model Observers
- Understanding Observer lifecycle methods
- Registering Observers using different approaches
- Implementing pre and post-event Observer methods

If you want to perform some action when the Eloquent object is created or updated, it is usually done with the Observer class. It's like events and listeners in Laravel, but all the listeners related to the same Eloquent Model are grouped into one class called Observer.


Generate Observers

Observer can be generated using the Artisan command. Typically, you should prefix Observer with the Model name for the name. Additionally, you can pass --model option and provide the Model name.

php artisan make:observer UserObserver --model=User

The command will generate the UserObserver class in the app/Observers folder. And then, in that Observer class, you will find generated methods, created(), updated(), deleted(), restored(), and forcedDeleted(). The last two are for Soft Deletes.

<?php
 
namespace App\Observers;
 
use App\Models\User;
 
class UserObserver
{
/**
* Handle the User "created" event.
*/
public function created(User $user): void
{
// ...
}
 
/**
* Handle the User "updated" event.
*/
public function updated(User $user): void
{
// ...
}
 
/**
* Handle the User "deleted" event.
*/
public function deleted(User $user): void
{
// ...
}
 
/**
* Handle the User "restored" event.
*/
public function restored(User $user): void
{
// ...
}
 
/**
* Handle the User "forceDeleted" event.
*/
public function forceDeleted(User $user): void
{
// ...
}
}

For example, you can send a notification to someone, notify the admin that the user was created, or inform the user themselves with some welcome email.

In this example, I will log that the user was created with the email.

app/Observers/UserObserver.php:

use App\Models\User;
 
class UserObserver
{
public function created(User $user): void
{
info('User was created: ' . $user->email);
}
 
// ...
}

Register Observers

It's not enough to generate an Observer. We need to register that into the system. Registration can be done in two ways. The first one uses...

The full lesson is only for Premium Members.
Want to access all 28 lessons of this course? (71 min read)

You also get:

  • 69 courses (majority in latest Laravel 11)
  • Premium tutorials
  • Access to repositories
  • Private Discord