Laravel 5 - How to use Primary key in pivot table?

Asked

Viewed 501 times

0

I have a question that came up now. You searched the forums, and I did not find anything like it. I have this scheme in my comic:

users: id name ...

products: id name ...

product_user: id product_id user_id ...

In my User.php, I have:

public function products()
{
    return $this->belongsToMany('App\Product')->withTimestamps();
}

Lááá in my view, I have an instance of User: @foreach($user->products as $product) // some code here... @endforeach

But, I can’t get the id of my pivot table like this:

@foreach($user->products as $product)
    {{ $product->pivot->id }}}
@endforeach

I can even get the other fields, for example:= {{ $product->pivot->created_at }}}

But the id, I can’t. When I give a dd() in $product->pivot, and I see the Attributes, I have this:

#attributes: array:4 [▼
    "user_id" => 2
    "product_id" => 1
    "created_at" => "2015-03-14 20:25:09"
    "updated_at" => "2015-03-14 20:25:09"
  ]

How do I get this goddamn pivot table ID?

1 answer

0


public function products()
{
    return $this->belongsToMany('App\Product')->withTimestamps()->withPivot("id");
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.