Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

ziben69's avatar

Displaying data from the database - complex query

Hello guys,

I have 3 tables in relationship:

Categories 1:N Products N:N Attributes

how can I display something like this:

Show attributes where category id = ?

I have in my view sidebar:

@foreach($categories as $category)
<div class="sidebar-box-2">
        <h2 class="heading mb-4"><a href="#">{{ $category->title }}</a></h2>
    <ul>
        @foreach( $category->product as $product)
        <li><a href="#">{{ $product->title }}</a></li>
        @endforeach                    
    </ul>
</div>
@endforeach

but it display only product from category. I would like to display attributes of products here.

In my controller I have this query:

$categories = Category::where('visible',1)->orderBy('order', 'asc')->with(['products'])->get();

Thanks for help

0 likes
5 replies
Sinnbeck's avatar

You can add an extra level like this

$categories = Category::where('visible',1)->orderBy('order', 'asc')->with(['products.attributes'])->get();

And

@foreach( $category->product as $product)
        <li><a href="#">{{ $product->title }}</a></li>
     @foreach ($product->attributes as $attribute) 
         {{$attribute->name}}
    @endforeach 
@endforeach
ziben69's avatar

Thanks, almost good. Now it display attributes to me as many times as there are products, and I need display only once

ziben69's avatar

But what when I have relationship like this:

Catalog 1:N Category 1:N Product N:N Attribute

if I do:

public function attributes()
    {
        return $this->hasManyThrough('Attribute', 'Product');
    }

in Catalog model I have error:

Call to undefined relationship [attributes] on model [App\Models\Category].

this is probably because there is still a category table along the way. There is only one intermediate table in the documentation.

Please or to participate in this conversation.