0


I'm using Laravel-Excel library to develop an export xls function.
I need to add a value to specific cell. As documentation, I wrote script

$data = MyModel::getComplexData();

Excel::create('Export payroll', function($excel) use ($data) {

    $excel->sheet('Sheet1', function($sheet) use ($data) {
        $sheet->cell('A1', function ($cell) use ($data) {
            $cell->setValue($data->name);
        });
    });

})->download('xls');

You can see parameter $data had been passed 3 times over 3 callback functions.
I need to find a way to make the script more clearly (pass $data only 1 time).

Thanh Dao
  • 1,218
  • 2
  • 16
  • 43
  • I don't see any other solution since if you use only once then $data variable will be undefined – Sagar Gautam Mar 14 '19 at 04:46
  • This is more clear actually. Future developer will exactly know where the `$data` is coming from. Alternative is to use `$GLOBALS` variable, but I won't recommend. – Jigar Mar 14 '19 at 05:03

1 Answers1

1

I have and idea look at the below code. we can set into member varibale.

<?php
class Test(){

    private $data = "Hellow";
    public function funct(){
        $data = MyModel::getComplexData();
        $this->data = $data;

        Excel::create('Export payroll', function($excel){

            $excel->sheet('Sheet1', function($sheet){
                $sheet->cell('A1', function ($cell){
                    $cell->setValue($this->data->name);
                });
            });

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

?>
ThataL
  • 165
  • 3
  • 12