Home > OS >  Nested foreach loops duplicate rows (Laravel 9)
Nested foreach loops duplicate rows (Laravel 9)

Time:01-10

I am currently working on my first real project with Laravel 9. I have come to a problem that I can't solve. I have two tables Categories and Articles and the they are connected with the field id (categories table) and category_id (articles table).

In my CategoryController:

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

My Blade view is setup like this:

            <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

When I check in I get this

            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

How can I solve this so it only says once No article under Category 5

CodePudding user response:

I would make sure your relationships in your models are set up.

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 quite sure about the blade part, but you should be able to do:

<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>
  • Related