Laravel - Undefined offset 0 - collection.php

To add another outcome, I was doing a "double" GroupBy on the collection:

$price_change->grouped_lines = $price_change->lines->groupBy('PriceListID')->transform(function($item, $k) {
      return $item->groupBy('StockID');
});

The above basically groups the collection by 2 keys so:

$price_change->grouped_lines[PriceListID][StockID]->

I received the "Undefined offset 0 - collection.php" error To fix it I had to first do a isset() on the first key then the second:

if(isset($price_change->grouped_lines[1]) && isset($price_change->grouped_lines[1][23]))

You make assumptions about that index being present, which may not always be the case. Your logic should be more thussly:

$st = isset($stay[0]) ? $stay[0] : false;
if ($st){
    //now you can use it safely.
}

Tags:

Php

Laravel 4