callam's avatar

Paginate Eager Loaded Relation

I have created an entity called Album which has Photographers and Photos. A Photographer can contribute a Photo to an Album. I have written a scope to order the Album's Photographers by recently contributed so the last Photographer to add a Photo to the Album would be first in the list. I am using the scope in an eager loading closure for the Album's photos and photographers relation. I would like to know how I can paginate these relations.

0 likes
2 replies
martinbean's avatar

@callam You can add constraints to your relationships when eager-loading:

$albums = Album::with(['photos' => function ($query) {
    $query->latest();
}])->get();

This will return the photos in order added, newest first, from which you can access the related photographer.

callam's avatar

@martinbean Yes, that is what I am using, what I need help with is writing the scope itself.

$albums = Album::with([
    'photos' => function ($query) {
        $query->orderBy('created_at');
    },
    'photographers' => function ($query) {
        $query->orderByTimeSinceContributedAPhotoToTheAlbum();
    }
])->get();

Please or to participate in this conversation.