aperezmi's avatar

Pagination with a hasMany relationship

Hello everyone,

I have an issue related to pagination when you have a hasMany relationship.

Let's say we have an 'authors' table, and each Author has many 'books'.

Using a form, I filter on different properties of the authors, e.g. 'country'.

Each author of this query has many books, and I want to paginate the books with one book per page, so I have something like:

-First 10 pages: the 10 books written by the first author. -Next 5 pages: the 5 books written by the second author.

And so on.

Thank you.

0 likes
1 reply
bobbybouwmann's avatar
Level 88

Well in that case you should do it the other way around

$country = request()->get('country');

$books = Book::with('author')->whereHas('author', function ($query) use ($country) {
    $query->where('country', $country);
})->paginate(1);

return view('books.index', compact('books'));

Please or to participate in this conversation.