Reputation: 83
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?
Upvotes: 0
Views: 162
Reputation: 167
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?
Upvotes: 1
Reputation: 144
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 use
merge()on query builders, so you can use
whereIn` to return ads where its status in [1,2]
like this:
$ads= Ad::whereIn('status', [1,2])->paginate(30);
Upvotes: 2