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

nhayder's avatar
Level 13

How to paginate hasMany relationship in user article query

i have hasMany relationship for user articles, This is my user model

    public function articles() // returining correct data
    {
        return $this->hasMany(Article::class); // this get all aricles related to a user
    }

in user controller im passing the data to the view like this

    public function articles($id)
    {
        $subscriber = User::find($id)->with('articles');
        return view('admin.subscribers.subscriberarticles', compact('subscriber'));

    }

im trying to paginate the articles inside the user query above but its not working for me,

    public function articles($id)
    {
        $subscriber = User::find($id)->with('articles')->paginate(10);
        return view('admin.subscribers.subscriberarticles', compact('subscriber'));

    }

is there is any other way to get this pagination done.

0 likes
8 replies
Tray2's avatar

I would do this instead

$articles = Article::where('user_id', $id)->paginate(10);
nhayder's avatar
Level 13

@Tray2 Yah that would would but i was hoping not make extra query rather than combine both queries in one

Tray2's avatar

Try adding

->with('users')

In your query you paginated the users and not the articles so switch it around.

Cronix's avatar

You have things reversed. ->find() executes the query, so that goes after everything else (like with). Model::with('relationship')->find($id).

1 like
nhayder's avatar
Level 13

@Cronix @Tray2 im getting the data correctly now but still cant paginate?

this is what i have now

        $subscriber = User::with('articles')->find($id);


    // when i return this, it shows the query below 
        return $subscriber; 

firstname: "Joshuah",
familyname: "Terry",
articles: [
    {
        id:1
        title: "Possimus veritatis 1",
    },
    {
        id:1
        title: "Possimus veritatis2",
    },
    {
        id:1
        title: "Possimus veritatis3",
    },
    {
        id:1
        title: "Possimus veritatis4",
    },
    {
        id:1
        title: "Possimus veritatis5",
    },

]

the articles array is not getting paginated

Cronix's avatar
Cronix
Best Answer
Level 67

Sorry, missed the paginate part...that's a bit different. You call paginate() on the relationship method.

$subscriber = User::find($id)->articles()->paginate(10);

This would probably do the same thing, but more verbose...

$subscriber = User::with(['articles' => function($query) {
    $query->paginate(10);
    // $query->latest()->paginate(10);  // order newest to oldest
}])->find($id);
1 like
nhayder's avatar
Level 13

@cronix Just one small thing i need to show pagination links for the user to navigate throughs records, {{$subscriber->articles->links()}} is not working.

Do you have any ideas on how to do this

2 likes

Please or to participate in this conversation.