Laravel: Get pivot data for specific many to many relation

LaravelRelationship

Laravel Problem Overview


My User model has many Target and vice versa. Now I've got a given User and given Target and I want to access pivot data from their relation. The pivot column is called type

How can I achieve this?

Laravel Solutions


Solution 1 - Laravel

On the relationships for both User and Target, tack on a ->withPivot('type') which will instruct Laravel to include that column. Then once you have your result set, you can access the field with $user->pivot->type.

If you're not iterating over a collection, but have a user and one of their targets and want the type field, you could use $target = $user->targets->find($targetId) and access the type with $target->pivot->type.

More at http://laravel.com/docs/4.2/eloquent#working-with-pivot-tables

Solution 2 - Laravel

You can also limit columns by passing array as 2nd arg to simplePaginate

$query->users()->simplePaginate($per_page, ['users.id', 'users.email']);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBernd StrehlView Question on Stackoverflow
Solution 1 - LaravelmaknzView Answer on Stackoverflow
Solution 2 - LaravelDazzleView Answer on Stackoverflow