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

Rahulniit's avatar

Fetch Records Using Query Builder inside a loop in view

First i get id from outer loop then, through id Fetch Records Using Query Builder inside inner loop in view.. Does any body know about this..

0 likes
12 replies
bobbybouwmann's avatar

Well don't! Let your controller fetch all the data and return that to your view. In general your view should only display things and not do queries.

Can you show your current code so we can show an improvement on that?

Rahulniit's avatar

Actually, i want subcategories inside foreach categories loop using category->id based

Rahulniit's avatar

I get Categories data using CategoriesServiceProvider class as i need this in several view pages.

public function boot() { view()->composer('partials.header',function($view){ $headerCategories=\DB::table('categories')->where('status','active')->get(); $view->headerCategories=$headerCategories; }); }

in view i used

@foreach($headerCategories as $categories) {{ $cid=$categories->c_id }}

@endforech

how to get sub categories records here inside foreach loop?

Rahulniit's avatar

I am new in laravel, I am unable to find answer help me here to get answer

Rahulniit's avatar

is it possible to call route and return subcategories records inside foreach loop in view?

rin4ik's avatar

try this. if I understand you correctly this is what you need.

@foreach($headerCategories as $categories) 
 @foreach($categories->c_id  as $subcategory)
//render here
{{subcategory->title}}
        
  @endforeach 

@endforech

if it's not please elaborate your question

Rahulniit's avatar

yes, exactly you are right, but how i will get subcategories here busing query builder

jlrdw's avatar

There are times when a report or something uses sql in a loop. As example: See last reply here: https://laracasts.com/discuss/channels/laravel/complex-query-for-a-report

But I'd only do it in view if the inner foreach had a huge result. In which case you need double pagination.

What if inner foreach had 125,000 (just example) results such as a large Fedex accounts receivable report.

  • One paginator for NEXT COMPANY for example
  • Another paginator for more results from current company (could be A/R)

But

For a large year end report it is much better to dump data to a local machine then:

  • Have an already ODBC connection set up
  • Use an efficient desktop database
  • I used to use Visual Foxpro, but no longer
  • But MS Access is good too
  • Run large report from Access

That's just the way I did things, somehow it worked.

Of course I know Fedex doesn't use Access for this, was an example. But the medium sized trucking company I worked for it worked great. And it was for monthly A/R, A/P reports.

Operations manager wanted printed out reports.

Rahulniit's avatar

Thank You for answer, i must read eloquent.

Please or to participate in this conversation.