Nested foreach loop repeats rows (Laravel 9)
P粉268654873
2023-08-31 18:57:33
<p>I'm currently working on my first real project using Laravel 9. I've encountered a problem that I can't solve. I have two tables "category" and "article" which are joined with fields id (category table) and category_id (article table). </p>
<p>In my CategoryController: </p>
<pre class="brush:php;toolbar:false;">public function categories(){
$categories = Category::all();
$articles = Article::all();
return view('category.categories')->with('cats',$categories)->with('arts',$articles);
}</pre>
<p>My Blade view is set up like this:</p>
<pre class="brush:php;toolbar:false;"><ul>
@foreach($cats as $cat)
<li>{{ $cat->name}}
<ul>
@foreach($arts as $art)
@if($cat->id == $art->category_id)
<li>{{ $art->title }}</li>
@else
<li>No articles</li>
@endif
@endforeach
</ul>
</li>
@endforeach</pre>
<p>When I checked in I got this</p>
<pre class="brush:php;toolbar:false;">Category 1
Article title 1
No articles
No articles
No articles
No articles
Category 2
No articles
Article title 2
No articles
No articles
No articles
Category 3
No articles
No articles
Article title 3
No articles
No articles
Category 4
No articles
No articles
No articles
Article title 4
No articles
Category 5
No articles
No articles
No articles
No articles
No articles</pre>
<p>How do I fix this so it only shows "No articles under category 5" once?</p>
I would make sure the relationship is established in your model.
In your category model:
Then, in your CategoryController:
I'm not sure about the blade part, but you should be able to do it: