Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ;)

like image 841
user2916349 Avatar asked Dec 17 '16 15:12

user2916349


1 Answers

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;
like image 63
Amit Gupta Avatar answered Oct 28 '22 15:10

Amit Gupta