phpmysqllaravelcollectionseloquent

Laravel 5.3 pagination on sortBy collection


Why the paginate method doesn't work on this example ?

$shopIds = Follower::whereUserId($user->id)->orderBy('created_at','desc')->get()->pluck('shop_id')->toArray();
            $shops = Shop::whereIn('id',$shopIds)->with('deals')->with('deals.likes')->paginate($this->perPage)->sortBy(function($likes) {
                return $likes->count();
            });
            dd($shops);

enter image description here

Thank's for help ;)


Solution

  • The paginate is just working fine but the sortBy method is creating the problem for you because when you use sortBy it returns a new collection.

    So finally your $shops is an instance of Illuminate\Support\Collection not of Illuminate\Pagination\LengthAwarePaginator.

    You can try it as:

    $paginated_shops = Shop::whereIn('id',$shopIds)
                      ->with('deals')
                      ->with('deals.likes')
                      ->paginate($this->perPage);
    
    $shops = $paginated_shops->sortBy(function($likes) {
            return $likes->count();
        });
    
    $shops = new LengthAwarePaginator($shops, $paginated_shops->total(), $paginated_shops->perPage());
    

    Remember to add use statement at the top of the class as:

    use Illuminate\Pagination\LengthAwarePaginator;