WallyJ's avatar

Paginating Eloquent Relational Query Results - Eager Loading

I'm trying to have a section on my contact view that shows contact notes, 4 per page, in a box that goes through pages without refreshing the page. This may require AJAX, but I'm just trying to get the pagination to show at the moment.

Here's my code. Since I'm using the "with" to eager load the "contactnotes", I don't know where to put the pagination function.

Contacts Controller:

//Look up contact chosen by URL
 $contacts = Contact::with(['contactnotes', 'deals.tasks'])->find($id);

// Check for correct user
        
if(auth()->user()->id !== $contacts->user_id){
   return redirect('/contacts')->with('error', 'That Is Not Your Contact');
}

// Update Last Seen Field for viewed contact
Contact::where('id', $id)
  ->update(['contactlastseen' => \Carbon\Carbon::now()]);

return view('contacts.show', ['contact' => $contacts, 'contactnotes' => $contacts->contactnotes, 'deals' => $contacts->deals]);

View:

<div class="col-md-12">
  <ul class="list-group">
    @foreach($contactnotes->sortByDesc('created_at') as $contactnote)
    <li class="list-group-item">
    {{$contactnote->created_at->diffForHumans()}} - {{$contactnote->contactnotetext}}
    </li>
    @endforeach
  </ul>
</div>

I may ultimately go with a static box with a scroll bar and add infinite scroll capabilities to it, so it doesn't take up much space on the screen and would also not require a page refresh.

Ideas? Thanks!

0 likes
3 replies
WallyJ's avatar

After rethinking my efforts, I believe I am going to switch to using JQuery to create an infinite scroll within the div that contains my data, rather than using pagination. No clicking needed, just the scroll wheel.

usman's avatar

@wallyj what is the problem? Why not use inside a view composer :

$contacts = Contact::with([....])->paginate(4);

? And yes nested loads are not paginated in this case.

Edit:

I think I misunderstood the problem. If you want to paginate the nested data, you can always create a paginator manually.

Update:

I think you can still use a view composer by using the ContactNotes model (if it is present) and using something like:

// assuming $id is retrieved from the request.
$contactNotes = ContactNotes::whereHas('contact', function($query) use ($id) {
    $query->where('contact_id', $id);
 })->paginate(4);

Hope this helps!

Please or to participate in this conversation.