php - Add data to collection before pagination in Laravel

934

I get some data from the database and do pagination with the following call:

$itemsList = DB::Table('items')->paginate(10);

Each item in the data has an expiry date associated with it, from which I calculate the number of days left and return as an array with a function I wrote. I need to somehow integrate this array into the pagination call in order for each page to display the correct days left value. At the moment, I have in my blade file something like this:

<?php
$i = 0;
?>
@foreach ($itemsList as $item)
    <tr>
        <td>{{ $item->item_name }}</td>
        <td>{{ $item->item_user }}</td>
        <td>{{$left_days[$i++]}}</td>

With this method the first page of pagination works fine, with the left_days array referring to the correct item in the list. On other pages however, the left_days values refer to the items of the first page, since the i value starts at 0 each run.

I think I need to add the left_days array into the collection before the pagination call, but I haven't been able to figure out how.

To be more specific, below is the result of dd on $itemList:

LengthAwarePaginator {#292 ▼
  #total: 94
  #lastPage: 10
  #items: Collection {#277 ▼
    #items: array:10 [▼
      0 => {#276 ▼
        +"id": 1
        +"item_name": "sadasd"
        +"item_user": "sadas"
        +"expiry_date": "2019-06-26"
        +"last_modified_by": "someone"
        +"created_at": "2019-06-18 15:19:33"
        +"updated_at": "2019-06-18 15:19:33"
      }
      1 => {#270 ▶}
      2 => {#279 ▶}
      3 => {#280 ▶}
      4 => {#281 ▶}
      5 => {#282 ▶}
      6 => {#283 ▶}
      7 => {#284 ▶}
      8 => {#285 ▶}
      9 => {#286 ▶}
    ]
  }
  #perPage: 10
  #currentPage: 1
  #path: "http://localhost:8000/licenses"
  #query: []
  #fragment: null
  #pageName: "page"
  +onEachSide: 3
  #options: array:2 [▶]
}

What I think I need is having a way to insert my array at the right locations such that each item in the collection also has a filed left_days that is calculated prior to the pagination.

2

Answer

Solution:

Answer given by Roland Starke and Tim Lewis:

Use:

Item::paginate(10);

instead of:

DB::Table('items')->paginate(10);'

and write a get function inside the model like this:

public function getLeftDaysAttribute(){
     calculations...
    return value;
}

After which I can simply call in the blade file the value of left_days:

 $item->left_days

People are also looking for solutions to the problem: PHP JSON Array Objects adding 0 as key

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.