How to observe Laravel Models and run actions while storing, updating, and deleting records

--

Observer classes have method names that reflect the Eloquent events you wish to listen for. Each of these methods receives the affected model as their only argument so you can add any logic to every event of your Model.

How to Create an Observe Class?

php artisan make:observer UserObserver --model=User

This artisan command will generate a file into app/Observers path with default methods that reflects functions of the model class.

To load Observer into our application, we have to set it into EventServiceProvider:

/**
* Register any events for your application.
*/
public function boot(): void
{
User::observe(UserObserver::class);
}

Now, we can insert any logic into Observer, this is a sample:

public function deleted(User $user)
{
$user->deleted_by = Auth::user()->id;
$user->save();
}

For a deep learning about Laravel Observer, visit: https://laravel.com/docs/10.x/eloquent#observers

--

--