Ad

How To Get Inserted Id Of Pivot When I Use Attach() In Laravel 5.6 (Eloquent)?

- 1 answer

I have this tables: users, programs and users_programs (pivot)

I use this sentence to relate users with programs (Many to Many)

$user->programs()->attach($program);

I want to get id to pivot table users_programs, it's posible? How I return id when save a row?

Thanks

Ad

Answer

Pivot tables don't have an increment id field in the realm of Eloquent.

If you want to get a specific program for a user in the pivot table, you can use something like the following approach as an example:

$user->programs()->attach($program->id);
$user = $user->fresh();
$userProgram  = $user->programs->keyBy('program_id')->get($program->id);
Ad
source: stackoverflow.com
Ad