mnlixk
mnlixk

Reputation: 21

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?

Upvotes: 0

Views: 14642

Answers (2)

keroles Monsef
keroles Monsef

Reputation: 741

you can do it via helper functions like this

    function resource_collection($resource): array
    {
        return json_decode($resource->response()->getContent(), true) ?? [];
    }

in you controller add the following

 return response()->json([
            'data' => resource_collection(BookResource::collection(Book::all())),
        ]);

Upvotes: 0

Fendy Harianto
Fendy Harianto

Reputation: 335

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

Upvotes: 2

Related Questions