Lars-Janssen's avatar

Eager loading pagination

Hello,

I've got this in my webapp:

$forum->load('topics');

It returns all related topics from a forum. But how would I paginate the topics?

0 likes
6 replies
SaeedPrez's avatar
Level 50

This would probably be the easiest way if you have the option to skip eager loading.

$topics = $forum->topics()->paginate(10);
WebKenth's avatar

Check out Laravel Pagination

I guess you could something in the lines of $forum->topics->paginate(10) which would return in chunks of 10

or if you are looking for some customized logic you could manually Chunk it and load it via an Ajax request

SaeedPrez's avatar

@WebKenth

I guess you could something in the lines of $forum->topics->paginate(10) which would return in chunks of 10

Note that calling a relation without () will actually execute the query and get all relationship rows from the database and then call ->paginate() on the collection that is returned. So make sure you have the parentheses when you plan to build on the query.

Edit:

Same issue with using chunk().. it suggest to get every single row in your database table and then chunk them up in your application and only use the small part you need. It's like going to the store every time you need milk and buying every single milk package there is and carrying them home and then throwing all of them away and keeping 1 ☺

1 like
Lars-Janssen's avatar

@SaeedPrez And now I do not get the forum information anymore (only the topics information). I receive this:

{
  "forum": {
    "total": 3,
    "per_page": 1,
    "current_page": 1,
    "last_page": 3,
    "next_page_url": "http://forum.dev/api/forum/test?page=2",
    "prev_page_url": null,
    "from": 1,
    "to": 1,
    "data": [
      {
        "id": 1,
        "slug": "test1",
        "name": "test",
        "description": "test description",
        "forum_id": 1,
        "created_at": null,
        "updated_at": null
      }
    ]
  }
}
SaeedPrez's avatar

@lars64 you already have the forum information in $forum and topics are in $topics with pagination.

And no, it's not a massive query, it's basically the same as $forum->load('topics') but it limits how many results are returned from database.

Please or to participate in this conversation.