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

Reiniger's avatar

Multiple relationships and use with Paginate

Relation structure

class User {
    public function students() {
        return $this -> belongsToMany(Student::class, 'users_students');
    }
}

class Students {
    public function groups() {
        return $this -> belongsToMany(Group::class, 'students_groups');
    }
    public function posts() {
        return $this -> belongsToMany(Post::class, 'posts_students');
    }
}

class Groups {
    public function posts() {
        return $this -> belongsToMany(Post::class, 'posts_groups');
    }
}

I can get all User -> Posts

$news = [];
foreach (User::find($id)->students AS $students){

    // get all posts by student
    foreach ($students->posts()->where('public', '=', 1)->orderBy('date', 'desc')->get() AS $value)
        $news[$value->id] = ['date' => $value->date, 'data' => $value];

    //get student groups
    foreach ($students->groups AS $groups){
        foreach ($groups->posts()->where('.public', '=', 1)->orderBy('date', 'desc')->get() AS $value)
            $news[$value->id] = ['date' => $value->date, 'data' => $value];
    }

}

Use $value->id to get unique Posts.

Posts also can be made without relations.

Maby my structure not made for my needs.

I tride, but there is just error.

User::find($id)->students()->posts()->paginate(50);

Is there posible way to get in the same time students -> posts and students->groups->posts by paginate?

0 likes
1 reply
shez1983's avatar

i think because you are doing find() - it actually does the QUERY so anything after this is not really a query.. try changing to

User::whereId($id)->students()->posts()->paginate(50);

but i dont really get what u want to paginate? u want to paginate by relationship?

Please or to participate in this conversation.