khawarraza's avatar

Pagination not working

I am trying to fetch few records from DB and applying pagination on results but pagination seems not to be working. Here is my code snippet:


Class City {
public function ads() {
        return $this->hasManyThrough('Sello\Ad', 'Sello\User');
    }
}


public function getAdsFeedWithFilters(Request $request) {

// fetch request params

$ads = $city->load(['ads' => function($query) use (
            $termsRS,
            $checkForSearchTerm,
            $checkForPostedWithin, $checkForPriceRange,
            $sortByColumn, $sortOrder, $postedWithin, $priceEndRange, $priceStartRange) {

            $query->where('status', '=', Ad::$STATUS_DRAFT);

            if ($checkForPriceRange) {
                $query->where('price', '>=', $priceStartRange);
                $query->where('price', '<=', $priceEndRange);
            }

            if ($checkForPostedWithin) {
                $query->whereRaw('creation_date >= NOW() - INTERVAL ' . $postedWithin . ' DAY');
            }

            if ($checkForSearchTerm) {
                $query->whereRaw("MATCH (title) AGAINST (?)", [$termsRS]);
            }

            $query->orderBy($sortByColumn, $sortOrder);

            $query->paginate(Ad::$ADS_PER_PAGE);

        }]);

// return results
return ResponseFormatter::format($code, $message, $ads);

}

I get the required results but result object does not contains fields like pageNo, totalPages, Next and Previous page urls etc.

0 likes
6 replies
khawarraza's avatar

I am not getting any error but the header fields which shows current page no, next page no, total pages and related urls are not being returned by the above query. I have updated my code snippet.

Snapey's avatar

i would definately suspect the response formatter. Just return the data and check its paginated

Cronix's avatar

Just a FYI you can save a line of code here:

if ($checkForPriceRange) {
    //$query->where('price', '>=', $priceStartRange);
    //$query->where('price', '<=', $priceEndRange);
    $query->whereBetween('price', [$priceStartRange, $priceEndRange]);
}
jcmargentina's avatar

totally not familiarized with

$ads = $city->load(['ads' => function($query) use ( ........

but did you try to actually var_dump($ads) and see that actually it has what is suppose to have???

Snapey's avatar

@jcmargentina made me look more closely at your code. you cannot paginate a relation.

to paginate ads that belong to a city, you must use the Ads model and not the city model

Please or to participate in this conversation.