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:
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?
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