0

I'm trying to access a variable from within my groupBy function in PHP within my Laravel project, but I'm getting an error suggesting that I have an undefined variable? I'm not quite sure why or how to access the variable I need...

public function getGroupingFormat($groupBy)
{
    switch (strtolower($groupBy)) {
      case 'hourly':
        $groupByFormat = 'Y-m-d ga';
        break;
      case 'daily':
        $groupByFormat = 'Y-m-d';
        break;
      case 'weekly':
        $groupByFormat = 'W';
        break;
      default:
        $groupByFormat = 'Y-m-d ga';
    }

    return $groupByFormat;
}

public function myFunction()
{
    $groupBy = 'Y-m-d';

    $results = $data->groupBy(function ($item, $key) {
      $date = Carbon::parse($item->date_at);

      // groupBy is undefined yet is defined above?
      return $date->format($this->getGroupingFormat($groupBy));
    });
}

Ryan H
  • 2,620
  • 4
  • 37
  • 109

1 Answers1

3

You need to pass $groupBy to your function. Notice the use after your function arguments which allows it to inherit variables from the parent scope.

public function myFunction()
{
    $groupBy = 'Y-m-d';

    $results = $data->groupBy(function ($item, $key) use ($groupBy) {
      $date = Carbon::parse($item->date_at);

      return $date->format($this->getGroupingFormat($groupBy));
    });
}
Peppermintology
  • 9,343
  • 3
  • 27
  • 51