Ahmed Alaa's avatar

How to paginate over two models' search results

I have two models: one for products the other one is for collections (collection of products) I want to make a search on both of them after the search completes, I concatenate the result to a single variable called items to be displayed in the view by foreach statement I have a problem with pagination as it's not supported for laravel collections I'm using livewire component

$totalItemsCollection = $collections->concat($products);
0 likes
5 replies
PovilasKorop's avatar

One of the ways to solve this is to transform the results into identical structure and merge into one collection, from there you can call pagination methods on it.

$products = Product::where('...')->get()->map(fn($product) => [
  'id' => $product->id,
  'name' => $product->name
]);
 
$collections = ProductCollection::where('...')->get()->map(fn($collection) => [
  'id' => $collection->id,
  'name' => $collection->name
]);
  
$results = collect()->merge($products)->merge($collections);
1 like
Ahmed Alaa's avatar

@PovilasKorop Firstly thank you for your reply to my question and thank you for your amazing series "laravel daily", I'm a big fan of it. I tried this way but I got an error when I used ->paginate() because it's not present as a method in laravel collection

Please or to participate in this conversation.