How to handle eloquent.deleted Event for all Models right?
To handle the eloquent.deleted
event for all models in Laravel, you can use the event listeners and the EventServiceProvider
. Here's a step-by-step guide to achieve this:
- Create a new listener file:
First, create a new listener file in the app/Listeners
directory. Let's call it ModelDeleted.php
.
<?php
namespace App\Listeners;
use Event;
class ModelDeleted
{
/**
* Handle the event.
*
* @param \Illuminate\Database\Eloquent\Model $model
* @return void
*/
public function handle($model)
{
// Your code here
}
}
- Register the listener:
Next, register the listener in the app/Providers/EventServiceProvider.php
file. Add the following code to the boot()
method:
protected function boot()
{
Event::listen(
'eloquent.deleted:*',
App\Listeners\ModelDeleted::class
);
}
This code registers the ModelDeleted
listener to listen for the eloquent.deleted
event on all models.
- Implement the logic:
Now, you can implement the logic you want to execute when a model is deleted in the handle()
method of the ModelDeleted
listener. For example, you might want to send an email notification or update a cache.
public function handle($model)
{
// Send an email notification
Mail::to('[email protected]')->send(new ModelDeletedEmail($model));
// Update a cache
Cache::forget('model_cache_key');
}
With this setup, the ModelDeleted
listener will be triggered whenever any model is deleted in your Laravel application.