tfevens's avatar

Pagination & Collections

In my app I'm currently displaying a list of articles, returned as an instance of Illuminate\Database\Eloquent\Collection. I can use $articles->shift() to grab the first article, and remove that from the Collection (displaying 2 articles, then an info box, and then looping through the remaining articles) without running into any issues.

However, now that I want to add pagination to the app, I'm being handed back an instance of Illuminate\Pagination\Paginator. This isn't allowing me to use $articles->shift() to pull the first 2 articles out. I'm not getting an error, but the same article is displayed three times.

Has anyone else ever come across this? If so, how did you go about working around it?

I have found out that if I modify Illuminate\Pagination\Paginator to extend Collection that everything works as I want, but this isn't really a viable option without it being added to the core Laravel files.

Any advice would be welcome!

0 likes
4 replies
JarekTkaczyk's avatar

@tfevens You can access underlying collection easily:

$paginator = Article::paginate(10);
$paginator->count();  // 10
$paginator->getCollection()->shift();
$paginator->count();  // 9
tfevens's avatar

@JarekTkaczyk, thanks for the response. I had missed that method completely.

However, it doesn't seem to be working.

$articles = Article::with('feed')
                ->orderBy('created_at','desc')
                ->paginate(10);
    echo $articles->count();
    $articles->getCollection()->shift();
    echo $articles->count();

is returning 10 on both occasions.

I can work around this by creating a new variable and assigning it the value of $articles->getCollection(), but that seems a little 'hacky'. Is there any reason why the method isn't chainable, or am I doing something totally off?

JarekTkaczyk's avatar

@tfevens You didn't say it was L4 ;)

In Laravel4 Paginator uses simple array, so try this:

$items = $paginator->getItems();
array_shift($items);
// then loop through $items or:
$items->setItems($items);
1 like
tfevens's avatar

Yeah, that was basically what I came up with too:

$pagination = Article::with('feed')
                ->orderBy('created_at','desc')
                ->paginate(17);

$articles = $pagination->getCollection();

Thanks!

Please or to participate in this conversation.