Search code examples
laravellaravel-5.5maatwebsite-excel

How to set a variable in laravel controller and use the value in exporting to excel


In my controller, I need to concatenate a string and a variable. After I concatenate it, i set it to variable $datenow. When i export to excel, I want to make the value of cell A2 to $datenow. But then i keep getting an error of Undefined variable: datenow. Here's my code:

public function userSummary()
{
    $mytime = Carbon\Carbon::now();
    $datenow = 'As of'.' '.$mytime;
    Excel::create('Empoyee Summary', function($excel) {

        $excel->sheet('Sheet1', function($sheet) {

            $sheet->setCellValue('A1', 'VCY Group of Companies');
            $sheet->setCellValue('A2', $datenow);

        });

    })->export('xls');      
}

How to put the value of cell A2 to $datenow?


Solution

  • Try this

    public function userSummary()
    {
        $mytime = Carbon\Carbon::now();
        $datenow = 'As of'.' '.$mytime;
        Excel::create('Empoyee Summary', function($excel) use ($datenow) {
    
            $excel->sheet('Sheet1', function($sheet) use($datenow) {
    
                $sheet->setCellValue('A1', 'VCY Group of Companies');
                $sheet->setCellValue('A2', $datenow);
    
            });
    
        })->export('xls');      
    }