Laravel Collection Set end date based on next record

68 views Asked by At

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
    }
 ]

This is what i got so far. Is there any better way?

$results->transform(function ($item, $key) use ($results) {
    $nextRecordDate = optional($results->get($key + 1))->effective_at;
    $end = $nextRecordDate ? Carbon::parse($nextRecordDate)->subDay()->toDateString() : null;

    $item->effective_end = $end;
    return $item;
});
1

There are 1 answers

0
Donkarnash On

Assuming that eloquent results is a collection of Models you can achieve the desired by either of the two


// Using object syntax
$results->map(function($item, $key) use($results) {

  $nextStart = $results->get($key+1) ? $results->get($key+1)->effective_at : null;  

  $end = $nextStart ? \Illuminate\Support\Carbon::parse($nextStart)->subDay()->toDateString() : null;

  $item->effective_end = $end;
  return $item;
});


//Using arrayable access

$results->map(function($item, $key) use($results) {
  
  $nextStart = isset($results[$key+1]) ? $results[$key+1]['effective_at'] : null;

  $end = $nextStart ? \Illuminate\Support\Carbon::parse($nextStart)->subDay()->toDateString() : null;

  $item['effective_end'] = $end;
  
  return $item;
});