Home > database >  Why is a observer class not working in model?
Why is a observer class not working in model?

Time:10-07

I have a Base model that I used to extend in all other Models. I created an observer for it called BaseObserver and registered it at boot method of EventServiceProvider. I have a creating event and would like to put my logic there every time I create a new other Model.

The problem is that the creating method in BaseObserver is not being called. But, when I created a closure for creating in Base model, it worked. What seems to be the problem here?

Base.php

namespace App\Models;

use Jenssegers\Mongodb\Eloquent\Model;
use Jenssegers\Mongodb\Eloquent\SoftDeletes;

class Base extends Model
{
    use SoftDeletes;

    protected $dates = ['deleted_at'];

    // This closure will work but If I commented this out, BaseObserver's creating method won't work
    protected static function booted()
    {
        static::creating(function ($base) {
            dd('hellp from base model');
        });
    }
}

BaseObserver.php

namespace App\Observers;

use App\Models\Base;

class BaseObserver
{
    public function creating(Base $base)
    {
        dd('hello from base obserer');

        $base->created_by = auth()->user()?->_id;
    }

    public function updating(Base $base)
    {
        dd('hello from base obserer');
        
        $base->updated_by = auth()->user()?->_id;
    }
}

EventServiceProvider.php

namespace App\Providers;

use App\Models\Base;
use App\Observers\BaseObserver;
use Illuminate\Auth\Events\Registered;
use Illuminate\Auth\Listeners\SendEmailVerificationNotification;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;

class EventServiceProvider extends ServiceProvider
{
    protected $listen = [
        Registered::class => [
            SendEmailVerificationNotification::class,
        ],
    ];

    public function boot()
    {
        Base::observe(BaseObserver::class);
    }

    public function shouldDiscoverEvents()
    {
        return false;
    }
}

Team.php

namespace App\Models;

use App\Models\Base;
use Illuminate\Database\Eloquent\Factories\HasFactory;

class Team extends Base
{
    use HasFactory;

    protected $fillable = [
        'name',
        'leader_id',
        'member_ids',
    ];
}

Result enter image description here

CodePudding user response:

it has to work

class Base extends Model
{
    protected static function booted()
    {
        static::observe(BaseObserver::class);
    }
}
  • Related