1
votes

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?

1

1 Answers

4
votes

Laravels Paginator class expects to be passed the records for the current page.

Firstly you will need to get the value for the current page. Then you will need to alter your query to only get the records for the current page:

// Get current page number
$page = 'Get this from the query string';

// Calculate the offset for current page
$offset = $perPage * ($page - 1);

// Get the records for the current page
$initialCollection = $this->model->orderBy('created_at', 'desc')->
                            skip($offset)->
                            take($perPage)->
                            get();

// Get total number of records in table
$totalRecords = $this->model->count();

// Paginate
$result = new Paginator($initialCollection, $totalRecords, $perPage);