Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

palla451's avatar

Update Pivot table of Many To Many Polimorph Relationship

Hi guys, i all this situation:

3 Tables

inputs


-id
-name
-money

outputs


-id
-name
-money

payments


-id
-name

paymentables


-payment_id         /* example id of payments*/
-paymentable_id     /* example id of inputs */
-paymentable_type /* example /App/Models/Input */

When update an input, how can i change in pivot table paymentable the payment_id ?

I have tried this way but without success:


$input = Input::with('payments')->find($request->input_id); /* input_id is the id of an Input */
$query = $input->payments()->updateExistingPivot([$request->payment],
                ['paymentable_id' => $request->input_id,
                'paymentable_type' => 'App\Models\Input']);
0 likes
3 replies
palla451's avatar

Input Model


    protected $fillable = [
         'name', 'money' 
    ];

    /**
     * Get all of payments method.
     */
    public function payments()
    {
        return $this->morphToMany(Payment::class, 'paymentable');
    }

Output Model


    protected $fillable = [
         'name', 'money' 
    ];

    /**
     * Get all of payments method.
     */
    public function payments()
    {
        return $this->morphToMany(Payment::class, 'paymentable');
    }

Payment Model


    protected $fillable = [
        'name'
    ];

    /**
     * Get all of the inputs that are assigned this tag.
     */
    public function inputs()
    {
        return $this->morphedByMany(Payment::class, 'paymentable');
    }
palla451's avatar
palla451
OP
Best Answer
Level 2

I resolve in update


$input->payments()->detach();
$input->payments()->attach($request->payment,[
                'paymentable_id' => $request->input_id,
                'paymentable_type' => 'App\Models\Input']);

return response()->json(['success'=>'Product saved successfully.']);

But I don't know if it's the best result

Please or to participate in this conversation.