So what are observers in Laravel and why you should use them?
1. Definition
Observers in Laravel help you to fire multiple events or do a CRUD operation in database!
When you create an observer, it will listen to a specific condition for a model, e.g: if user create a post and he/she achieved a certain level, the observer will fire related method(event) and do what ever you wrote!
2. Real Example
In this world websites, there are so many things we want to do after a user registered in our website! e.g: send an email, send SMS and etc... So why not leave them to Observers!
First, run this command to make a user observer (for User model):
php artisan make:observer UserObserver --model=User
Second, you will see four methods in it, that will run when their condition are true. these methods are:
namespace App\Observers;
use App\Models\User;
class UserObserver
{
/**
* Will do what you want When an instance of model created
*
* @param \App\Models\User $user
* @return void
*/
public function created(User $user)
{
//
}
/**
* Will do what you want When an instance of model updated
*
* @param \App\Models\User $user
* @return void
*/
public function updated(User $user)
{
//
}
/**
* Will do what you want When an instance of model deleted
*
* @param \App\Models\User $user
* @return void
*/
public function deleted(User $user)
{
//
}
/**
* Will do what you want When an instance of model force deleted
*
* @param \App\Models\User $user
* @return void
*/
public function forceDeleted(User $user)
{
//
}
}
You should know there is some other functions like: creating, updating, saving, afterSaving, restore
and etc... so you have a handful feature observer for many situations.
Maybe we just want to send a welcome message to user whenever he/she registered!
we may use create()
method, as below:
public function created(User $user)
{
Mail::to($user)->send(newUserRegisteredMailable($user));
}
And third one is registering our observer in the boot method of your application's App\Providers\EventServiceProvider
service provider:
use App\Models\User;
use App\Observers\UserObserver;
/**
* Register any events for your application.
*
* @return void
*/
public function boot()
{
User::observe(UserObserver::class);
}
That's it.
Top comments (3)
Nice
Straight to the point. Nothing to add..
Thanks!