How to get inserted id of pivot when I use attach() in Laravel 5.6 (Eloquent)?
How to get inserted id of pivot when I use attach() in Laravel 5.6 (Eloquent)?
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
unsigned integer
You can fetch your data like this:
User::find($userID)->programs()->get()
– AH.Pooladvand
2 days ago
User::find($userID)->programs()->get()
1 Answer
1
Pivot tables don't have an increment id field in the realm of Eloquent
.
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->save();
$userProgram = $user->programs()->where('program_id', $program->id)->first();
I believe you can also do:
$userProgram = $user->programs->keyBy('program_id')->get($program->id);
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Basically it is not recommended to use ID in your pivot tables because pivot tables are designed to store huge amount of data so if you use ID in your pivot table you can break
unsigned integer
max length.– AH.Pooladvand
2 days ago