Observer classes have method names that reflect the Eloquent events you want to listen for. Each of these methods receives the affected model as its only argument, so you can add any logic to every event of your model.
How do you create an observer class?
php artisan make:observer UserObserver --model=User
This Artisan command generates a file in the app/Observers path, with default methods that mirror the events of the model class.
To load the observer into our application, we register it in the EventServiceProvider:
/**
* Register any events for your application.
*/
public function boot(): void
{
User::observe(UserObserver::class);
}
Now we can put any logic into the observer. Here is a sample:
public function deleted(User $user)
{
$user->deleted_by = Auth::user()->id;
$user->save();
}
For a deeper dive into Laravel observers, see: https://laravel.com/docs/10.x/eloquent#observers