Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel excel passing a view

Tags:

php

excel

laravel

I'm trying to export data to excel and I can't seem to make it work. I am using: http://www.maatwebsite.nl/laravel-excel/docs

and I'm following the docs as much as I can. So I have this view which I'm trying to get in excel. The docs are telling me:

Loading a view for a single sheet

$sheet->loadView('folder.view');

So I did that, and (of course) I get an error saying that the variables in the views are not declined since I'm not passing the variables into the view. So I read the docs again and it says:

Passing variables to the view

Alternatively you can use the with() method which works the same as with Laravel views.

with a basic with() example.

So now I have this in my controller function:

public function something(){
$something2='';
$something='';
Excel::create('Laravel Excel', function($excel) {

    $excel->sheet('Excel sheet', function($sheet) {
        $sheet->loadView('something')->with('something',$something)
                                     ->with('something2',$something2);
        $sheet->setOrientation('landscape');
    });

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

now I get an error in the controller:

undefined variable $something

So I didn't know what could be going wrong. I remained positive and thought it would be something easy like $something actually not being declared, so I removed that from the excel exporting. Then it gave me the error:

undefined variable $something2

After this I knew there was something else wrong. Since both aren't 'defined' according to the excel creation. So I tried out something new. Declaring both variables inside of the excel creation. Al though there is more code between the declaring of the variables and the excel creation. So this wouldn't work. So the code is like this:

$something2='';
$something='';
//more code
if($check==true){
Excel::create('Laravel Excel', function($excel) {

So I'm still stuck.

What is going wrong here? Am I misunderstanding this excel creation stuff?

like image 893
Loko Avatar asked May 19 '15 07:05

Loko


1 Answers

I think this might be the problem, since you're using cloasures, the variables is not accessable in the cloasure without defining the use of them.

public function something(){

    $something2='';
    $something='';

    Excel::create('Laravel Excel', function($excel) use ($something, $something2) {

        $excel->sheet('Excel sheet', function($sheet) use ($something, $something2) {
            $sheet->loadView('something')->with('something',$something)
                                         ->with('something2',$something2);
            $sheet->setOrientation('landscape');
        });

    })->export('xls');

}
like image 76
oBo Avatar answered Nov 08 '22 12:11

oBo