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

ReakyMark's avatar

how to make relationship in Eloquent with this Query Builder

product
-----------------------------------------------------

product_id | product_name | ... | category_id

1                    | product_1           | 1
2                   | product_2           | 2


category
-----------------------------------------------------
category_id | category_name 

1                       | type_1
2                      | type_2

my expect result to make category as Main Header and list lastest porduct under category name

this is my Query Builder in order to get what i want above but i wanna know how to do it in Eloquent relationship ?

@foreach($loadCategory as $cat)
  @php
    $loadProduct = $productObj::where('category_id','=', $cat->category_id)
                                 ->orderBy('product_id', 'DESC')
                                 ->paginate(1);
  @endphp

  @if(count($loadProduct) > 0)
                      
    @foreach($loadProduct as $prod)
                           
        <div class="item">                 
            <div class="home-button">
                <img src="{{ asset('assets/my_lib/images/product/' . $prod->product_image) }}" alt="">
            </div>
            <div class="home-button">
                <p class="category-list-p">{{$cat->category_name}}</p>
                <p>Latest Product</p>
                <p>{{$prod->product_name}}</p>
                <a href="{{asset('product/'. $cat->category_name) }}">See All</a>
            </div>
        </div>
                        @endforeach
                    @endif
                @endforeach
0 likes
3 replies
shez1983's avatar

you have to read the docs.. i feel like i would be repeating whats there already...

create relationships in models..

& then reference them here.. a clue: u wud do $category->products() for example to get all products.. to get one you could create another relationship (similar to previous to get all products) but limit it to get just one product

ReakyMark's avatar

@shez1983 Thank and 1 more question how can i count how many Query and how many second on page load it take to my bottom of UI Page ?

shez1983's avatar

you can you the network tab of chrome/firefox to see how long the page loads - you can also install a package debugbar (google it) and it will tell you how long each query took to run

Please or to participate in this conversation.