Nested foreach loop repeats rows (Laravel 9)
P粉268654873
P粉268654873 2023-08-31 18:57:33
0
1
447

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).

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 set up like this:

    @foreach($cats as $cat)
  • {{ $cat->name}}
      @foreach($arts as $art) @if($cat->id == $art->category_id)
    • {{ $art->title }}
    • @else
    • No articles
    • @endif @endforeach
  • @endforeach

When I checked in I got 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 do I fix this so it only shows "No articles under category 5" once?

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:

    @foreach($cats as $cat)
  • {{ $cat->name}}
  • @if(empty($cat->articles))
  • No articles
  • @else
      @foreach($cat->articles as $art)
    • {{ $art->title }}
    • @endforeach
    @endif @endforeach
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template
    About us Disclaimer Sitemap
    php.cn:Public welfare online PHP training,Help PHP learners grow quickly!