Support the ongoing development of Laravel.io →
Database Eloquent Views

I couldn't use the paginate()-method anymore cause I needed to add an extra attribute to every element in my collection. The result is that I get the right pagination when rendering but it's always showing all elements on every page.

public function allPaginate($perPage)
{
    $initialCollection = $this->model->orderBy('created_at', 'desc')->get();

    // adding slug to my collection for every item
    $initialCollection->each(function ($item) {
        if(! isset($item->slug))
        {
            $slug = Str::slug($item->title);
            $item->slug = $slug;
        }
    });

    $result = new Paginator($initialCollection, count($initialCollection), $perPage);
    $result->setPath(Request::url());

    return $result;
}

Before i just used this:

$paginator = $this->model->orderBy('created_at', 'desc')->paginate($perPage);

I have 3 elements in my database and I want to show 2 per page. Here are the dumps of the two versions.

As it should be (with the ->paginate()) with 2 items in the collection

LengthAwarePaginator {#362 ▼

#total: 3

#lastPage: 2

#items: Collection {#364 ▼

#items: array:2 [▼

  0 => News {#365 ▶}

  1 => News {#366 ▶}

]

}

#perPage: 2

#currentPage: 1

#path: "http://jv.app/nl/nieuws/"

#query: []

#fragment: null

#pageName: "page"

}

As it is now (with new Paginator::make()) with 3 items in the collection

LengthAwarePaginator {#358 ▼

#total: 3

#lastPage: 2

#items: Collection {#368 ▼

#items: array:3 [▼

  0 => News {#369 ▶}

  1 => News {#370 ▶}

  2 => News {#371 ▶}

]

}

#perPage: 2

#currentPage: 1

#path: "http://jv.app/nl/nieuws"

#query: []

#fragment: null

#pageName: "page"

}

What is the issue here?

Last updated 2 years ago.
0

I did got it working turning things around:

public function allPaginate($perPage)
{
    $result = $this->model->orderBy('created_at', 'desc')->paginate($perPage);

    // adding slug to my collection for every item
    $result->each(function ($item) {
        if(! isset($item->slug))
        {
            $slug = Str::slug($item->title);
            $item->slug = $slug;
        }
    });

    return $result;
}
Last updated 9 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

bflydesign bflydesign Joined 21 Nov 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.