Nested foreach loop repeats rows (Laravel 9)
P粉268654873
P粉268654873 2023-08-31 18:57:33
0
1
556
<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>
P粉268654873
P粉268654873

reply all(1)
P粉111641966

I would make sure the relationship is established in your model.

In your category model:

public function articles()
{
    return $this->hasMany(Article::class);
}

Then, in your CategoryController:

public function categories(){
    $categories = Category::with('articles')->get();
    return view('category.categories')->with('cats',$categories);
}

I'm not sure about the blade part, but you should be able to do it:

<ul>
  @foreach($cats as $cat)
    <li>{{ $cat->name}}</li>
    @if(empty($cat->articles))
      <li>No articles</li> 
    @else
      <ul>
        @foreach($cat->articles as $art)
          <li>{{ $art->title }}</li>
        @endforeach
      </ul>
    @endif
  @endforeach
</ul>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template