KodaC's avatar
Level 1

Observers is not called

I use Laravel 10 and have registered an Observer

class AdObserver
{
    /**
     * Handle the Ad "deleting" event.
     */
    public function deleting(Ad $Ad): void
    {
        $ad->products()->delete();
        Storage::disk('public')->delete('....' . $ad->ad1_file);
    }
}
class EventServiceProvider extends ServiceProvider
{
    /**
     * The event to listener mappings for the application.
     *
     * @var array<class-string, array<int, class-string>>
     */
    protected $listen = [
        Registered::class => [
            SendEmailVerificationNotification::class,
        ],
    ];

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

    /**
     * Determine if events and listeners should be automatically discovered.
     */
    public function shouldDiscoverEvents(): bool
    {
        return false;
    }
}

A command to delete old entries

private function deleteOldEntries()
    {
        $ads = Ad::where('created_at', '<', Carbon::now()->subSeconds(10))->delete();
    }

My entries are deleted, but it seems that my Observer is not accessed

0 likes
3 replies
LaryAI's avatar
LaryAI
AI
Best Answer
Level 58

It looks like you have registered the observer correctly, but you are not using the model's delete() method in your deleteOldEntries() function. Instead, you are using the query builder's delete() method. The model's delete() method will trigger the observer, while the query builder's delete() method will not.

To fix this, you can use the model's delete() method instead:

private function deleteOldEntries()
{
    $ads = Ad::where('created_at', '<', Carbon::now()->subSeconds(10))->get();
    foreach ($ads as $ad) {
        $ad->delete();
    }
}
1 like
KodaC's avatar
Level 1

The problem was that I directly executed delete. With the foreach loop it works.

kokoshneta's avatar

@KodaC Indeed. The documentation notes this:

When executing a mass delete statement via Eloquent, the deleting and deleted model events will not be dispatched for the deleted models. This is because the models are never actually retrieved when executing the delete statement.

1 like

Please or to participate in this conversation.