simcha's avatar

no run 'static::retrieved' if it call from relation method

I have 'static::retrieved' in the X model that have a function that iterates over children

When I call the father from the child I don't want to runnig this event, how?

0 likes
5 replies
tisuchi's avatar

@simcha Like this?

class X extends Model
{
    protected static function booted()
    {
        static::retrieved(function ($model) {
            // This event will not be triggered when accessing the relationship method
            if (!app()->runningInConsole() && !app()->runningUnitTests()) {
                // Event Logic
            }
        });
    }

    public function children()
    {
        // Disable events for this query
        return $this->hasMany(Child::class)->withoutEvents();
    }
}
simcha's avatar

@tisuchi

Call to undefined method Illuminate\Database\Eloquent\Relations\HasMany::withoutEvents()
Snapey's avatar

If the child models have a FK to the father, delete them using DB method

DB::table('children')->where('father_id', $father->id)->delete();

which will also be more performant than iterating over models.

simcha's avatar

My problem was the call caused more models to be retrieved thus creating a recursion

In the end you found and I did this:

//Parent.php
 protected static function booted()
    {
        static::retrieved(function ($model) {
                self::withoutEvents(fn() => ... );
        });
    }

//Child.php
    public function children()
    {
        return $this->hasMany(Child::class);
    }

Please or to participate in this conversation.