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...