Thanh Toàn
Thanh Toàn

Reputation: 145

Laravel-excel: What does it pass a variable.

I have source code in my Controller.php :

public function excel($id)
    {
         try
        {

            Excel::create('Hoadondiennuoc',function($excel){
            $excel->sheet('Hóa đơn điện nước',function($sheet){
                $diennuoc=Diennuoc::find($id);
                 $data=[
                'diennuoc'=>$diennuoc,
                ];
                $sheet->loadView('backend.diennuoc.diennuoc-excel',$data);
            });
           })->download('xlsx');

        }
        catch(QueryException $ex)
        {
            return response(['error'=> true ,'message'=> $ex->getMessage()],200);
        }
        catch(PDOException $ex)
        {
            return response(['error'=> true ,'message'=> $ex->getMessage()],200);
        }
    }

When i run my code, the error is: Undefined variable: id This code is used for exporting a excel file. The issue is that i can't use "$id" variable from : "public function excel($id)" for implementing a statement :"$diennuoc=Diennuoc::find($id)". Do you have ideas to how to use $id variable in that? Thank you very much.

Upvotes: 1

Views: 539

Answers (1)

Maraboc
Maraboc

Reputation: 11093

You have to add use keyword, because the variable $id is not defined in the scope of the anonymous function :

$excel->sheet('Hóa đơn điện nước',function($sheet) use($id){
    $diennuoc=Diennuoc::find($id);
     $data=[
    'diennuoc'=>$diennuoc,
    ];
    $sheet->loadView('backend.diennuoc.diennuoc-excel',$data);
});

Upvotes: 2

Related Questions