Support the ongoing development of Laravel.io →
Eloquent Database

Hey.

I need to get the ID of pivot when inserting related items in Many to Many. Ex.

$pivot_id = $person->forms()->attach($form->id);

Is there a way to retrieve the id ?

Last updated 2 years ago.
0

I modified the code from the post a little :

$pivot_id = $form->persons()->where("persons.id", "=",$person->id)->withPivot("id")->orderBy('pivot_created_at', 'desc')->first()->pivot->id;

Then i get the latest inserted pivot_id

0

Sign in to participate in this thread!

Eventy

Your banner here too?

Bolandish bolandish Joined 2 Jun 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.