Skip to content

Paginated Resources

Ivan Babenko edited this page Apr 21, 2021 · 1 revision

Introduction

The purpose of this example is to show how to use Paginated results in combination of Laravel Eloquent API Resources.
Documentation for API Resources : https://laravel.com/docs/eloquent-resources

Example

Here you have a simple BookResource :

class BookResource extends JsonResource
{
    /**
     * @param Request $request
     * @return array
     */
    public function toArray($request): array
    {
        return [
            'id' => $this->id,
            'title' => $this->title,
            'description' => $this->description,
            'isbn' => $this->isbn
        ];
    }
}

Below you can see a simple paginated search on the title or description of the book.
The paginated results is then sent to the BookResource collection.
class BookController extends Controller
{
    public function search(BookSearchRequest $request)
    {
        $search = Book::boolSearch();
        $search->must('multi_match', [
            'type' => 'phrase',
            'query' => $request->input('search'),
            'fields' => ['title^3', 'description']
        ]);
        
        // Paginate
        $books = $search->paginate(10);
        // Important to make BookResource aware of the paginated collection
        $books->setCollection($books->models());
        // If you want to append current query string to links and meta data generated by the Paginator
        $books->appends($request->query());

        return BookResource::collection($books);
    }
}
Clone this wiki locally