58

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?

Carrie Kendall
  • 11,124
  • 5
  • 61
  • 81
Bernd Strehl
  • 2,852
  • 4
  • 24
  • 43

3 Answers3

102

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

maknz
  • 3,746
  • 3
  • 24
  • 21
4

Laravel 8.x

After accessing the relationship, you can access the intermediate table using the pivot attribute on your models

foreach ($user->targets as $target) {
    echo $target->pivot->created_at;
}

Docs: https://laravel.com/docs/8.x/eloquent-relationships#retrieving-intermediate-table-columns

pszaba
  • 1,034
  • 9
  • 16
0

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

$query->users()->simplePaginate($per_page, ['users.id', 'users.email']);
Dazzle
  • 2,880
  • 3
  • 25
  • 52