Nazareno Lorenzo
Nazareno Lorenzo

Reputation: 1079

How to paginate through joined records on laravel?

I'm using Laravel 4.1.x and I have a Has Many and Belongs To Many relationship between Tags and Photos (A photo belongs to many tags, a tag belongs to many photos). I'm using a pivot table with tag_id and photo_id

I know how to paginate the tags, using:

Tag::paginate($limit);

I'm able to fetch one tag with all the related photos using:

Tag::find($id);

But what I want to do now, is to retrieve all the photos that belongs to a tag , but paginating them. So, its something like the second code that I show, but with a page and limit parameter.

For example, I would want to see the first 15 photos that belongs to the tag with id=1, and be able to after that select the second 15.

Update: Based on the answer provided, I tried with ->photos()->paginate(), but using this, it doesn't returns the rest of the informaton from the tag (Name, description, etc).

I've been able to get everything using:

$tag = Tag::findOrFail($id)->toArray();
$tag['photos'] = Tag::findOrFail($id)->photos()->paginate($limit)->toArray();

But I'm not sure if there is any other way to do this, and if this is generating an extra query.

Upvotes: 0

Views: 795

Answers (1)

user1669496
user1669496

Reputation: 33058

Have you tried...

Tag::find(1)->photos()->paginate(15);

If you need to display information on the tag, there are a few ways. Eager loading is usually best but in this case because we know the tag id, we aren't being faced with the n+1 problem so it may look a bit more confusing than it needs to be.

$limit = 15;
$tag = Tag::with(array('photos' => function($q) use ($limit)
{
    $q->paginate($limit);
}))->find(1);

    // Use
echo $tag->name;
foreach($tag->photos as $photo) {
    echo $photo->description;
}

Or you can just do what we did earlier except split it up a bit to save the individual parts.

$tag = Tag::find(1);
$photos = $tag->photos()->paginate(15);

// use
echo $tag->name;
foreach($photos as $photo) {
    echo $photo->description;
}

Upvotes: 2

Related Questions