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

Croisciento's avatar

Pagination with many to many relationships

Hey, I've been trying to figure how to set a pagination system when you have many to many relationships.

Basically I got 3 tables. articles, promotions and article_promotion. An article is created by an user and he can pick up a promotion which has a starting and ending date.

The index view should be retrieving all the articles where one of its promotion associated has its ending date which isn't deprecated.

As such I'm trying to achieve something like this :

$articles = Promotion::current()->articles()->paginate(6);

public function scopeCurrent($query)
    {
        $query->where('starting_date', '<=', Carbon::now())->where('ending_date', '>=', Carbon::now());
    }

But for some reason I get this error :

Call to undefined method Illuminate\Database\Eloquent\Collection::articles()

Even though I got the relationship established in my Model as such :

Promotion.php

    public function articles()
    {
        return $this->belongsToMany('App\Article');
    }

Article.php

public function promotions()
    {
        return $this->belongsToMany('App\Promotion');
    }

Is an additional relationship required? I've been trying some solution I've found here and there without success. Thanks !

0 likes
2 replies
pmall's avatar
pmall
Best Answer
Level 56

You are calling the relationship method on the query builder (what return the scope Current) and not on the promotion model.

If you want to get all articles having current promotions use whereHas :

$articles = Article::whereHas('promotions', function ($q) {
    $q->current();
})->paginate(6);
Croisciento's avatar

Alright thanks, that was it. I've checked the documentation but guess I didn't check it enough time. :)

Please or to participate in this conversation.