ziben69
3 months ago
567
2
Laravel

Laravel - display only 3 records from relationship

Posted 3 months ago by ziben69

Hello guys,

In my controller I have query:

$categories = Category::where('visible',1)->orderBy('order', 'asc')->with(['products'=>function($q) {
    $q->where('visible', 1)->orderBy('order', 'asc')->get()->take(3);
}])->get();

when I try to display 3 product from categories it doesn't work. It display all products...

My view:

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

How can I display only 3 products from category? Thanks so much!

Please sign in or create an account to participate in this conversation.