0

I have problems using data inside a laravel function, here is a example:

    public function csvUnique($id){ 

          $date1= ''.$id.' 00:00:00';
          $date2= ''.$id.' 23:59:59';       

        \Excel::create('Customer list', function ($excel) {

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

             echo  $date1; 
             echo  $date1; 

             });

            })->export('csv');

} //end csv

$id is passed value,and I can see value if use dd($id). The problem is: How to pass values date1 and date2 inside functions?

I tried with global, same error:

**Undefined variable: date1**
Federico J.
  • 15,388
  • 6
  • 32
  • 51
pavlenko
  • 625
  • 2
  • 11
  • 30

1 Answers1

3

You have to inject the variables into the scope of the closure. This is done with use:

\Excel::create('Customer list', function ($excel) use ($date1, $date2) {

     $excel->sheet('Sheetname', function ($sheet) use ($date1, $date2) {
         echo  $date1; 
         echo  $date1; 
     });

})->export('csv');

In your case you have to do it twice. First pass it inside the first anonymous function and from there to the second one.

Take a look at this answer for a very detailed explanation of the whole topic. The section Crossing scope boundaries is especially relevant for your question.

Community
  • 1
  • 1
lukasgeiter
  • 147,337
  • 26
  • 332
  • 270