'How to create a filter by category in MANY TO MANY relationship in Laravel?
I have a many to many between Article and Category model and a pivot containing category_id and article_id records. At the click on the category link I would have a page that shows me all articles related to the category clicked but i can't create the right function in the controller.
public function showcategory($id){
$articles=Article::whereHas('categories',function($query){
$query->whereIn('category_id', $id);
})->get();
return view('categorydetail',compact('articles);
}
Solution 1:[1]
Your code seems not fine. Eloquent whereIn
is expecting an array as second parameter. Use where
instead.
$articles=Article::whereHas('categories',function($query){
$query->where('category_id', $id);
})->get();
Ideally, this is not the best practice. You'd better try the flow below:
//Category.php
public function articles() {
return $this->belongsTo(Article::class);
}
//Controller
$category = Category::with('articles')->find($id);
if (empty($category)) {
//show 404 error or redirection
}
$articles = $category->articles()->get();
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Huy Ph?m |