Laravel 8 Observer not triggered
I am a big fan of Laravel observer. It actually allows us to create an observer for laravel models which observe the model events like create, update, delete events.
We often use the laravel observers to send the notification or update other records when certain events occur in the laravel model.
Laravel observer not working (solved)
But, I encountered this error that laravel observer does not trigger when a specified event occurs. Like I have updated the model record but the subsequent observer was not triggered.
Product::where(‘id’, $id)->update([‘status’ => ProductStatus::OUT]);
After a little research about it, I found that it observes the updates after the last retrieve of the record. So, I have changed the update query below.
$product = Product::where(‘id’, $id)->first(); $product->update([‘status’ => ProductStatus::OUT]);
Firstly, I have fetched the record and then updated it. This way it triggers the update event for our observer.
Create Observer class
To generate a laravel observer for any model run the below command:
php artisan make:observer ProductObserver --model=Product
In the observer below we have all related event handling methods like created, updated, deleted, and it can also handle soft delete events.
class ProductObserver { protected $afterCommit = true; /** * Handle the Product "created" event. * * @param \App\Models\Product $product * @return void */ public function created(Product $product) { event(new ProductCreated($product)); } /** * Handle the Product "updated" event. * * @param \App\Models\Product $product * @return void */ public function updated(Product $product) { if( $product->wasChanged(‘status’) ) { event(new ProductUpdated($product)); } } /** * Handle the Product "deleted" event. * * @param \App\Models\Product $product * @return void */ public function deleted(Product $product) { // } /** * Handle the Product "restored" event. * * @param \App\Models\Product $product * @return void */ public function restored(Product $product) { // } /** * Handle the Product "force deleted" event. * * @param \App\Models\Product $product * @return void */ public function forceDeleted(Product $product) { // } }
Register an observer in the event service provider
In the App\Providers\EventServiceProvider
, we simply need to register this observer in the boot method.
public function boot() { Product::observe(ProductObserver::class); }
That’s it, laravel observer working not triggered.
Hope it will help you, see you in the next tutorial.