CodexBloom - Programming Q&A Platform

Laravel 9 Observer Not Triggering on Model Events with Soft Deletes

👀 Views: 50 💬 Answers: 1 📅 Created: 2025-06-03
laravel observers soft-deletes PHP

I'm updating my dependencies and I'm dealing with I'm a bit lost with I'm attempting to set up I'm sure I'm missing something obvious here, but I'm using Laravel 9 and trying to implement model observers for a `User` model that has soft deletes enabled... The issue I’m encountering is that the observer methods (`created`, `updated`, `deleted`) are not being called when I perform actions like creating or soft deleting a user. Here’s what I have in my `User` model: ```php namespace App\Models; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\SoftDeletes; class User extends Model { use SoftDeletes; protected $fillable = ['name', 'email']; } ``` I've set up my observer in the `App\Providers\EventServiceProvider` like this: ```php namespace App\Providers; use Illuminate\Database\Eloquent\Model; use App\Models\User; use App\Observers\UserObserver; class EventServiceProvider extends ServiceProvider { public function boot() { User::observe(UserObserver::class); } } ``` And my `UserObserver` looks like this: ```php namespace App\Observers; use App\Models\User; class UserObserver { public function created(User $user) { // Log user creation } public function deleted(User $user) { // Log user deletion } } ``` I’ve verified that the observer is registered correctly and that `UserObserver` is being loaded, as I placed some log statements in the constructor. However, when I run the following code in my controller: ```php $user = User::create(['name' => 'John Doe', 'email' => 'john@example.com']); $user->delete(); ``` The `created` and `deleted` methods in `UserObserver` are never called. I checked the Laravel documentation on observers and soft deletes, and I don’t see anything that explicitly states that observers won’t work with soft deletes. I’ve also confirmed that the model is indeed set to use soft deletes by checking the database, and I see that the `deleted_at` column gets populated when I call `delete()`. I've tried clearing the cache using `php artisan config:cache` and `php artisan optimize:clear`, but it didn’t resolve the issue. Is there something I’m overlooking regarding how observers work with soft deletes in Laravel 9, or any specific configurations I need to set? Any help would be greatly appreciated! What am I doing wrong? This issue appeared after updating to Php 3.9. Is there a simpler solution I'm overlooking? I'm working in a Windows 11 environment. Thanks for any help you can provide! Any ideas how to fix this? This issue appeared after updating to Php 3.10. My development environment is macOS. Am I approaching this the right way?