Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

axis's avatar
Level 1

Paginate collection

Hi, is it possible to paginate colletion in Laravel ?

I've 5 tables : markets, benefit_market, benefits, benefit_item, items and these 3 models behind.

Markets have multiple benefits and benefits have multiple items

//Market.php

class Market extends Model
{
    public function benefits()
    {
        return $this->belongsToMany(Benefit::class);
    }

    public function getItemsAttribute()
    {
        return $this->benefits
            ->pluck('items')
            ->collapse();
    }
}
//Benefit.php

class Benefit extends Model
{
    public function items()
    {
        return $this->belongsToMany(Item::class);
    }

    public function markets()
    {
        return $this->belongsToMany(Market::class);
    }
}
//Item.php

class Item extends Model
{
    public function benefits()
    {
        return $this->belongsToMany(Benefit::class);
    }

    public function getMarketsAttribute()
    {
        return $this->benefits
            ->pluck('markets')
            ->collapse()
            ->unique('id');
    }
}

Since a market, i access to all items of all benefits for given market with : $market->items.

But now, I'ld like paginate this result and i don't know how do that...

//MarketController.php

class MarketController extends Controller
{
    public function show(Market $market)
    {
        $items = $market->items->paginate(10); // it doesn't work !

        return view('pages.markets.show', compact('market', 'items'));
    }
}

Hope someone can help me. Thanks. :)

0 likes
9 replies
jlrdw's avatar

I'm on mobile now, not at my saved links. But if you do a Google search on laravel paginate collection you will find some previous answers I've given one myself, sorry again not at links right now.

Snapey's avatar

try

$items = $market->items()->paginate(10);
axis's avatar
Level 1

jlrdw i serach on google like that but i found only olders methods...

Snapey, it doesn't work because items is an attribute, not relation :'(

Snapey's avatar

confusing with having a relationship with the same name...

axis's avatar
Level 1

In the same idea, there is the forPage() method. But you can generate màualy pagination links...

I prefer use previous example used in the gist.

Thanks for your helps !!

jlrdw's avatar

Generating pagination links is just simple styling ( the bootstrap CSS). active, disabled, etc.

Experiment and use a combination of the methods for collections as needed.

But the splice is a starting point.

Please or to participate in this conversation.