0

I am using the Laravel Excel project to export data to an Excel file. I am able to generate a file with the correct data using hard coded month and year values, like so

 public function month() {

    Excel::create('New file', function($excel) {
        $excel->sheet('New sheet', function($sheet) {
            $data = new ReportModel;
            $year = (int)2016;
            $month = (int)9;
            $donationData = $data->getDayData($month, $year);
            $sheet->loadView('exports.month', array('donationData' => $donationData));
        });
    })->download('xlsx');
}

However, when I try to make the month and year variables, using the following code

 public function month($month, $year) {

    Excel::create('New file', function($excel) {
        $excel->sheet('New sheet', function($sheet) {
            $data = new ReportModel;
            $year = (int)$year;
            $month = (int)$month;
            $donationData = $data->getDayData($month, $year);
            $sheet->loadView('exports.month', array('donationData' => $donationData));
        });
    })->download('xlsx');
}

I get the following error

Access to undeclared static property: App\Http\Controllers\ExportController::$year

I understand this is down to variable scope, but can't get my head round the PHP docs. I have tried

$year = (int)self::$year;

but am getting the same result.

terrorfall
  • 1,121
  • 3
  • 16
  • 33

2 Answers2

2

Try inheriting the variables you need access to inside the anonymous function scope.

$example = function () use ($message) {
    var_dump($message);
};

http://php.net/manual/en/functions.anonymous.php

Something like:

Excel::create('New file', function($excel) use ($year, $month) {
    $excel->sheet('New sheet', function($sheet) use ($year, $month) {
        $data = new ReportModel;
        $year = (int)$year;
        $month = (int)$month;
        $donationData = $data->getDayData($month, $year);
        $sheet->loadView('exports.month', array('donationData' => $donationData));
    });
})->download('xlsx');
terrorfall
  • 1,121
  • 3
  • 16
  • 33
Pistachio
  • 1,652
  • 1
  • 18
  • 38
  • Thanks, @Pistachio worked a charm. Also had to apply the same logic to the $excel->sheet function as well in order for it to work. – terrorfall Sep 12 '16 at 09:49
1

You're correct in your assumption that it's about variable scope, so you need to "import" the $year and $month variables in the callback's scope, refactor the call like this and it should work:

Excel::create('New file', function($excel) use ($year, $month) { ...
kalatabe
  • 2,909
  • 2
  • 15
  • 24