Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

AhmadYousef's avatar

access the 3rd table in many to many

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 !

0 likes
7 replies
AhmadYousef's avatar

Actually your solution kept giving me the results for all categories, not only the category_id = 1 :(

Anan's avatar

try,


class Category extends Model
{
    public function articles()
    {
    return $this->hasManyThrough('App\Article', 'App\ArticleCategory', 'article_id', 'id');
    }
}


class Article extends Model
{
    public function category()
    {
    return $this->hasManyThrough('App\Category', 'App\ArticleCategory', 'category_id', 'id');
    }
}

AhmadYousef's avatar

Hi @Anan , I don't have ArticleCategory class, I made one but now it gives me this error:

SQLSTATE[42S02]: Base table or view not found: 1146 Table 'asabia.article_categories' doesn't exist (SQL: select `categories`.*, `article_categories`.`category_id` from `categories` inner join `article_categories` on `article_categories`.`id` = `categories`.`id` where `article_categories`.`category_id` in (7, 8, 9, 10, 11, 12, 13, 14, 15, 16))

I changed the table name but it gave me another error with column names, I don't think this is the issue ..

Anan's avatar

You need to create model App/ArticleCategory


class ArticleCategory extends Model
{
    protected $table = 'article_categories';
}


rickshawhobo's avatar
Level 1

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);
});

2 likes

Please or to participate in this conversation.