Search code examples
laravelpaginationloadingeager

Laravel 5.5 Paginate the Query - Eager Loading


I have a problem and can't figure out how to solve it. I've searched online but still couldn't get a firm answer. What I'm trying to do is to paginate Inquiries table - or the query below. Everything seems to work (at least I'm getting 20 inquiries per page, however I can't figure out how to display the links()?

I'm saving Inquiries in the $thecusts collection and passing it to the view. Tables and relations : Employees - Dealers (manytomany) Dealers-customers(1 to many) Customers-inquiries (1 to many).

So I need to paginate x Inquiries for the employee that has many dealers.

Anyone can help ?

$justch = $me->employeehasdealers()->get(['dealers.dealer_id','dealer','abbreviation']); //list of dealers assigned to auth employee
$justch2=$justch->load(['DealerHasInquiries'=>function($query){
    $query->with('inquiriescomments:comments_inquiries_id,inquiry_id,employee_id,comments','inquiryspdl','inquiriescustomers:customer_id,customer')->paginate(20);
}]);


$thecusts = new Collection();
foreach ($justch2 as $just) {
    $thecusts = $thecusts->merge($just->DealerHasInquiries);
}

Solution

  • The problem is you're not passing back the paginator instance. You can manually create one in your controller based on $thecusts:

    $perPage=20;
    return view('my-view', ['paginator' => new Paginator($thecusts->toArray(), $perPage)]);
    

    Then you can call the links method on the paginator instance in your view:

    {{ $paginator->links() }}
    

    Edit

    You may be able to simply all this though in a single query like:

    $thecusts = $me->employeehasdealers()->with(['DealerHasInquiries'=>function($query){
        $query->with('inquiriescomments:comments_inquiries_id,inquiry_id,employee_id,comments','inquiryspdl','inquiriescustomers:customer_id,customer');
    }])->paginate(20);
    
    return view('my-view, compact('thecusts'));