Skip to content
Advertisement

Laravel: Passing parameters from function to Excel export

I have a laravel function that exports a Database query to Excel. I’m using MaatwebsiteExcelFacadesExcel.

The problem is I’m trying to pass 2 dates as parameters but when I do so I get an Undefined variable error.

Mi question is how can I pass this variables from the main function to the excel function. Here’s my code:

    public function excel2 (Request $request){
   


// These are the values I want pass to the query: 
$initialDate=$request->get('initialDate');
$finalDate=$request->get('finalDate');



        
        Excel::create('DataByDate',function($excel){

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

            $data =DB::select('SELECT c.cuenta,g.fecha as fecha, t.descripcion as tipificacion, 
                g.observacion as comentario, ROUND(NVL(c.saldoVencido,0),2) AS SaldoVencidoQ, ROUND(NVL(saldoVencidoD,0),2) AS SaldoVencidoD, ROUND(NVL(c.saldo,0),2) AS SaldoQ, ROUND(NVL(c.saldoD,0),2) AS saldoD,
                ROUND(NVL(c.montoExtraf,0),2) AS MontoExtraf,c.cuotasVencidas AS CuotasVencidasQ, NVL(c.cuotasVencidasD,0) AS cuotasVencidasD, c.responsable AS Gestor from gestion g   
                    inner join cliente c on g.idCliente = c.id 
                   
                   inner join tipificacion t on g.idTipif = t.id_tipif
                    where esPromesa!="R"
                    // This part is the one that is failing
                    and cast fecha as date  between '.$initialDate.'  and '.$finalDate.';
                    ');

            
            $data= json_decode( json_encode($data), true);
            $sheet->fromArray($data,null,null,true);                   
            });    
        
        })->export('xls'); 
    
    }

Advertisement

Answer

If you need to use variables in the closure scope, you should use the use() statement. This would look like this.

Excel::create('DataByDate', function ($excel) use ($initialDate, $finalDate) {

    $excel->sheet('DataByDate', function ($sheet) use ($initialDate, $finalDate) {

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement