MorphToMany relation empty in `created` Model Observer

767 Views Asked by At

I am using Laravel Nova and have an Entry model that uses spatie/nova-tags-field. (Under the hood this package uses a morphToMany relation between models and tags via a trait)

I attached a model observer on the created event.

I want to access the entry's tags in the observer like this:

public function created(Entry $entry)
{
    $tags = $entry->tags;
}

But $tags is always an empty array [], yet I can access the models tags later (not in the observer, but anywhere else) using Entry::find($id)->tags. My guess is that the morphToMany pivot table entry for the attached tags is being created after the observer fires?

Thank for your input.

1

There are 1 best solutions below

2
Olivenbaum On

You could override the attachTags method in your Entry and fire a custom event when $this->wasRecentlyCreated is true.

Also you could listen to the created event (or any other) of your own tag model.
In combination with $touches something close to your desired behaviour may be possible. But obviously the created event of your Entry will always be fired before any tags are attached.