【问题标题】:Laravel: Passing parameters from function to Excel exportLaravel:将参数从函数传递到 Excel 导出
【发布时间】:2021-01-15 16:22:27
【问题描述】:

我有一个将数据库查询导出到 Excel 的 laravel 函数。我正在使用 Maatwebsite\Excel\Facades\Excel。

问题是我试图将 2 个日期作为参数传递,但是当我这样做时,我得到一个未定义的变量错误。

我的问题是如何将这些变量从主函数传递到 excel 函数。这是我的代码:

    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'); 
    
    }

【问题讨论】:

  • 欢迎来到 SO ... 你想通过什么?
  • 别忘了包含你的 Laravel 版本。

标签: php laravel


【解决方案1】:

如果需要在闭包范围内使用变量,则应使用use() 语句。这看起来像这样。

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

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

【讨论】:

  • 非常有用,效果很好,非常感谢。
猜你喜欢
  • 1970-01-01
  • 2011-03-25
  • 1970-01-01
  • 2016-08-07
  • 2013-12-07
  • 2022-01-25
  • 2022-01-27
  • 1970-01-01
  • 2016-04-26
相关资源
最近更新 更多