Observing models and relationships
Hi,
I have 2 models for example say
Library
and Book
. On my Library create page I can select the books that belong to this library. When I save the library, the books are also saved in the relationship table.
I have a LibraryObserver
so that I can perform some processing when it is created - however, the processing involves the books too.
The issue I have is that in the public function created(Library $library)
method of my LibraryObserver
the relationship doesn't exist yet (presumably because it hasn't been saved at this point - because we're firing on the Library
created event).
Anyone have any ideas how I can get around this?
One option is to add all the logic into the form schema in the after create (I think) but I'd like it to be centralised logic rather that attached to the form.
Thanks in advance π9 Replies
Can you explain what kind of processing is necessary?
Not really in my example above π
The real example is to do with payments and invoices - when we receive invoices I want to check payments and if there's any outstanding balances that don't match then we create extra payments - and do some different checks regarding VAT etc. Book == Payment and Invoice == Library. So when the Invoice is created, I want to look at the attached payments - but they don't seem to be saved in the relationship at this point (in the created method in the observer)
I guess you are using a repeater then? You can use
->dehydrated(false)
and the data should be included in the afterCreated hook.
If you want to stick to observers: Probably best to hook into Payments and get the invoice for the payment and then do your processing. That probably needs some denouncing thoughI'm using a CheckboxList with the relationship set - but I guess it follows the same as a repeater
Yep
I was originally doing it by dispatching an event in the afterCreate method (arguably, I could have just out the logic there rather than creating an event) - but it's still the same where it's tied to the create page when ideally, I want it tied to the model so that if it's created some other way, potentially API, then it's triggered also
You could create a
Pivot
model and add the Observer on that one. Then it really only fires after Payments are attached. But I don't think that gets you any further. Hooking into the models itself is nice, but doesn't seem like the best solution in your case.Aye I think that's the same but different. Cheers for your help π
I'd just wrap the logic in an Action (action pattern) and call that from a Filament hook
That lets you reuse the code in other places. An event would be a similar solutions if you prefer that.