0

I am facing a problem with sorting and returning merged collections.

When i do:

$ads = Ad::where('status',1)->where('deleted_at',NULL)->paginate(30);

it works but when i merge this with another collection like

$one = Ad::where('status', 1)->get();
$two = Ad::where('status', 2)->get();
$ads = $one->merge($two);
$ads->paginate(30);

it tells me that "paginate method does not exist" as well as "orderBy method does not exist"

are those collections different from the single returned ones?

Desory
  • 83
  • 2
  • 11

2 Answers2

2

This is because you are returning a collection from $one and $two and then trying to paginate them, which you can not paginate collections, you can only paginate query builder now to return query builder from $one and $two remove get(),but now you cant usemerge()on query builders, so you can usewhereIn` to return ads where its status in [1,2] like this:

$ads= Ad::whereIn('status', [1,2])->paginate(30);
  • works just fine ty, i wish i could paginate collections tho because: I want collection 1 [ICE CREAM; TOHUWABOHU] and collection 2 [A ; B ; B ; C ; D; D;] to be shuffled in their own array before merging them, so it looks like [TOHUWABOHU; ICE CREAM; A B C D D B] or something like that. Is that the case when i do it with your approach , too? i mean, do they get randomly sticked together or are they one after another? – Desory May 28 '19 at 10:45
  • they will be randomly ordered, but if you want to order then you can use [orderBy](https://laravel.com/docs/5.8/queries#ordering-grouping-limit-and-offset) like this: `$ads= Ad::whereIn('status', [1,2])->orderBy('status')->paginate(30);` – Khawlah Elshah May 28 '19 at 11:14
  • but that would order mix the two of them right? i meant more like , imagine having groups, one group of boys and one of girls, then you sort them by Age , and merge them. then you have the boys sorted by age , followed by the girls sorted by age, but not the entire collection is sorted. – Desory May 29 '19 at 00:24
1

Pagination only works on the query builder and Eloquent query.

Laravel Pagination adjusts the MySQL Query to only retrieve the results from that specific page.

Because you already have the query result it can no longer be used to apply pagination. However you can still slice the collection to multiple parts for your pages.

In your case, since you use the same model, you better retrieve both results:

$ad = Ad::where('status', 1)->orWhere('status', 2)->paginate(20);

If you use different models, you can slice the collection as shown here: stackoverflow - How can I paginate a merged collection in Laravel 5?

John
  • 158
  • 4
  • 7