How to get the current relationship entry on a RelationManager action?
My goal is to get the current relationship information, let me explain. Let's say that I have an Order model, a Product model and a many to many relationship between them using BelongsToMany in both models. I'm using a relation manager to attach products to an order.
For example, If I use this on an AttachAction
->after(function (RelationManager $livewire) {
dd($livewire->mountedTableActionData['recordId'];
$livewire->emit('refresh');
})
That "recordId" is the id of the product that was attached via the relationship. However, is there a way to access the pivot table information? Let's say I have a pivot table named "order_products", every time I "attach" a product to an order, there's a new entry on that table.
Is there like an event that is emitted as described in the Form Builder documentation? Or maybe in the livewire object that I use in the callback? Where do I found that recently created row in the pivot table?11 Replies
$record->pivot?
I think a Model instance of the current data is only available in forms, not in Relation Manager actions. I know that because I just got an error trying your advice hahaha, not an expert here
$this->record->pivot?
what do you want to do with the pivot record when you get access to it
I want to update a column that must not be updated in the form.
after() has access to
$data['recordId']
so you could use that to fetch the pivot record
also using $livewire->ownerRecord
Ok, that's interesting. In my very simple example, what exactly is $data['recordId']? Is it the id of the product? Also, what is $data? Is it an instance of the RelationManager object?
AttachAction is a table action
so read the table action docs
$data is the data that comes out of the action form
recordId is the name of the Select
so the ID of the product you selected
Hey, first of all, thanks for your help, I really appreciate it. Also, I've read this docs many, many times https://filamentphp.com/docs/2.x/admin/resources/relation-managers#attaching-and-detaching-records and there's not a single reference to that. Maybe there are some other docs about the AttachAction? I would love to read them.
I get what you're saying. That ID is exactly the one that I do not want. Because if I go to the relationship through the ownerRecord, that "product" ID is already in the pivot table, many, many times, since it's a many to many relationship. I just want the last record that Laravel created on that pivot table. Not the "order" record, not the "product" record, the one in between that was created in the pivot table.
yes but you use that ID to fetch the pivot record
either fetch it and then update, or use updateExistingPivot() like in my example
the reason why $data isnt in the Attach docs is because its a generic table actions thing, its not an Attach thing, it works everywhere
Ok, thank you. I'll try now and I'll see what's inside that $data.