Laravel Collection Set end date based on next record

  laravel, laravel-collection

I have this result returned by Eloquent. Already sorted effective_at Ascending

[
    {
      "id": 2200155,
      "price": "0.07980",
      "effective_at": "2020-10-01"
    },
    {
      "id": 2218010,
      "price": "0.07870",
      "effective_at": "2020-10-06"
    },
    {
      "id": 2256374,
      "price": "0.07960",
      "effective_at": "2020-10-15"
    },
    {
      "id": 2273713,
      "price": "0.08460",
      "effective_at": "2020-10-19"
    },
    {
      "id": 2300540,
      "price": "0.08460",
      "effective_at": "2020-10-26"
    }
 ]

I want to add loop the collections and append a new attribute effective_end based on the date of the next records. Null if there is no next record

Expected output as below:-

[
    {
      "id": 2200155,
      "price": "0.07980",
      "effective_at": "2020-10-01",
      "effective_end": "2020-10-05"
    },
    {
      "id": 2218010,
      "price": "0.07870",
      "effective_at": "2020-10-06",
      "effective_end": "2020-10-14"
    },
    {
      "id": 2256374,
      "price": "0.07960",
      "effective_at": "2020-10-15",
      "effective_end": "2020-10-18"
    },
    {
      "id": 2273713,
      "price": "0.08460",
      "effective_at": "2020-10-19",
      "effective_end": "2020-10-25"
    },
    {
      "id": 2300540,
      "price": "0.08460",
      "effective_at": "2020-10-26",
      "effective_end": null
    }
 ]

Source: Laravel

Leave a Reply