Playing Next Lesson In
seconds

Let's Learn AdonisJS 6 #8.6

How To Paginate Filtered Query Results

In This Lesson

We'll learn about AdonisJS Model Query Builder pagination and walk through an example of how we can easily paginate the results of our filtered movies.

Created by
@tomgobich
Published

Join the Discussion 1 comments

Create a free account to join in on the discussion
  1. @tomgobich

    Hey all! Somehow, I completely missed that there's a queryString method available on the paginator that allows us to define additional query string key/values. We'll patch this in down the road, but wanted to make a note here that it is available!

    async index({ request, view, auth }: HttpContext) {
      const page = request.input('page', 1)
      const filters = await movieFilterValidator.validate(request.qs())
      const movies = await MovieService.getFiltered(filters, auth.user).paginate(page, 15)
      const movieStatuses = await MovieStatus.query().orderBy('name').select('id', 'name')
      const movieSortOptions = MovieService.sortOptions
      const qs = querystring.stringify(filters)
    
      movies.baseUrl(router.makeUrl('movies.index'))
     movies.queryString(filters)
    
      const rangeMin = movies.currentPage - 3
      const rangeMax = movies.currentPage + 3
      let pagination = movies.getUrlsForRange(1, movies.lastPage).filter((item) => {
        return item.page >= rangeMin && item.page <= rangeMax
      })
    
      if (qs) {
        pagination = pagination.map((item) => {
          item.url += `&${qs}`
          return item
        })
      }
    
      return view.render('pages/movies/index', {
        movies,
        movieStatuses,
        movieSortOptions,
        filters,
        pagination,
        qs,
      })
    }
    Copied!
    2