Achraf Ben Soltane
Achraf Ben Soltane

Reputation: 304

How to merge collection and Query builder then use paginate on it Laravel 8

I have a builder object and a collection and i want to combine them and use paginate of laravel.

How can i do that ?

public function getRequests(){
        $closedRequests = request::join('request_logs', 'request_logs.request_id', '=', 'requests.id')
                    ->select("requests.id", "requests.user_id", "requests.form_type", "requests.created_at", "requests.request_status")
                    ->whereNotIn('request_status', [-2, 0])
                    ->where('request_logs.user_id', Auth::user()->id);

        $processingRequests = request::select("requests.id", "requests.user_id", "requests.form_type", "requests.created_at", "requests.request_status")
                         ->where('request_status', 0)
                         ->get()
                         ->filter(function ($request) {
                               return FormsController::checkUserPermissionToConsultForm($request, true);

        });
        $closedRequests = $closedRequests->union($processingRequests)
                            ->orderBy('created_at', 'desc')
                            ->paginate(5);
        return $closedRequests;
    }

The function above is what i tried to do but it generate an error saying

Call to a member function getBindings() on array

Upvotes: 0

Views: 896

Answers (1)

Mehedi Hassan
Mehedi Hassan

Reputation: 396

Well, there is no default method available to do such things in Laravel. What you can do is you can make one by using the Illuminate\Pagination\Paginator or Illuminate\Pagination\LengthAwarePaginator depending on your need. Illuminate\Pagination\Paginator refers to the simplePaginate() method where Illuminate\Pagination\LengthAwarePaginator refers to paginate method.

Another way could be converting the builder result into the collection. Then merge the builder collection and the $processingRequests collection and use forPage() method which is also a collection method to generate pagination with some modification.

Here are the references:

Custom Pagination: https://laravel.com/docs/8.x/pagination#manually-creating-a-paginator

forPage:

https://laravel.com/docs/8.x/collections#method-forpage https://stillat.com/blog/2018/04/22/laravel-5-collections-paginating-collections-with-forpage

Upvotes: 1

Related Questions