Search code examples
laravellaravel-paginationlaravel-resource

Laravel API resource paginate sub data


I'm trying to understand Laravel API resource and would like to know how I could use pagination with a subset of my data. For example: I have a book model and to return all the books available I could write:

return BookResource::collection(Book::paginate());

This would return all the books I have, but what if I want to return only books written by a specific author. For example:

$books = Book::where('author_id', 1)->get();

How can I paginate this data and return it via BookResource to the client?


Solution

  • In your controller you can do it like this

    public function index(Request $request) {
        $books = Book::where('author_id', 1)->paginate();
        return BookResource::collection($books);
    }
    

    just pass params page to get the page that you want and read this for your reference

    https://laravel.com/docs/9.x/pagination#basic-usage

    https://laravel.com/docs/9.x/eloquent-resources#resource-collections