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.
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.
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) { // } }
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.
Today we are going to learn about managing multiple PHP versions on ubuntu with xampp.…
Let's understand about how to use coding to improve your website's SEO. In today’s computerized…
Let's understand the most important linux commands for web developers. Linux, as an open-source and…
Today we are going to discuss top 75+ Laravel interview questions asked by top MNCs.Laravel,…
Today we will discuss about the Mailtrap integration with laravel 10 .Sending and receiving emails…
Today we are going to integrate FCM (Firebase Cloud Messaging) push notifications with ionic application.Firebase…