Does this work?
$market->with(benefits.items)->pluck('benefits.items');
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
Hi, i try to access data over 2 belongsToMany relationships.
I've 5 tables : markets, benefit_market, benefits, benefit_item, items and these 3 models behind.
Markets have multiple benefits and benefits have multiple items
//Market.php
class Market extends Model
{
public function benefits()
{
return $this->belongsToMany(Benefit::class);
}
}
//Benefit.php
class Benefit extends Model
{
public function items()
{
return $this->belongsToMany(Item::class);
}
public function markets()
{
return $this->belongsToMany(Market::class);
}
}
//Item.php
class Item extends Model
{
public function benefits()
{
return $this->belongsToMany(Benefit::class);
}
}
I want to access all items for a given market (and reverse access all markets for given items) like this : $market->items but i don't know how to do it.
I've tried $market->with(benefits.items)->get() but i can't access directly to all items for the market...
Hope someone can help me. Thanks. :)
Try something like this: https://stackoverflow.com/a/26187648
Or you can use an accessor to your Market model:
public function getItemsAttribute()
{
return $items = $this->benefits->pluck('items')->collapse()->unique('id');
}
Then in your controller you can do something like this:
$market = Market::with('benefits.items')->first();
dd($market->items);
// or this
$markets = Market::with('benefits.items')->get();
foreach($markets as $market) {
dd($market->items);
}
Please or to participate in this conversation.