You need to use a closure for that
$articles = Article::with(['category' => function ($query) {
$query->where('category_id', 1);
}])->paginate(10);
See: https://laravel.com/docs/master/eloquent-relationships#querying-relations
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
Hi ! I have 3 tables: articles: id,title,body article_category: article_id,category_id categories: id,name
my classes:
class Category extends Model
{
public function articles()
{
return $this->belongsToMany('App\Article');
}
}
class Article extends Model
{
public function category()
{
return $this->belongsToMany('App\Category');
}
}
What I need is to list the articles with the category ID =1
what I tried (with no luck) :
// (1)
$articles = Category::where('id','1')->articles()->paginate(10);
// error: Call to undefined method Illuminate\Database\Query\Builder::articles()
// (2)
$articles = Article::with('category')->where('category_id','1')->paginate(10);
// error: Column not found: 1054 Unknown column 'category_id' in 'where clause'
How can I access this table?, do I have to join those 3 tables? , Isn't there a faster way?
Thank you !
Can't believe no one has given you the answer. You do it like this.
$categoryId = 1;
$articles = Article::whereHas('category', function ($q) use ($categoryId) {
$q->where('id', $categoryId);
});
Please or to participate in this conversation.