DaveLV2
DaveLV2

Reputation: 358

Combining two collections and paginating them

So I have ads in a database. There are 3 types for the ads. Featured, bold and free. I want to display them in a page. First based on what category has been selected. I want to show all featured first by added date and then after that all bold and free items by added date. And I want to paginate them.

I have tried this:

    $adsFeatured = Ads::where('category', '=', $category)->where('status', 'enabled')->where('type', 'featured')->get();
    $adsOther = Ads::where('category', '=', $category)->where('status', '=', 'enabled')->where('type', '=', 'free')->orWhere('type', '=', 'bold')->get();
    $adsOther->merge($adsFeatured);
    $adsFeatured->paginate(15);

But ofcourse it cannot be paginated if I use get(), but if i dont use it then i cant merge them, i want to merge them because i hope it would place them in that order.

Thanks for help, and I hope I have explained everything properly. :)

Upvotes: 1

Views: 190

Answers (1)

lukasgeiter
lukasgeiter

Reputation: 152870

You should be able to do that in one query. Try this

$ads = Ads::selectRaw('*, IF(type = "featured",1,0) AS is_featured')
          ->where('category', $category)
          ->where('status', 'enabled')
          ->orderBy('is_featured', 'desc')
          ->orderBy('created_at', 'desc')
          ->paginate(15);

Upvotes: 1

Related Questions