Search code examples
eloquentlaravel-5.1maatwebsite-excel

use Eloquent relationships while exporting data to Excel file in Laravel


I want to create a summary report of my two tables, one is employees table and the other one is sims table. These tables have one to many relationship. I know that we can export data of a model by using ->fromModel($model) but is there a way so I can generate the report based on the two tables?


Solution

  • SO, I asked a question and someone who could not answer but cowardly awarded -1. However, I figured it how to do this manually. Posting the code so it may help the future beginners like me.

    public function downloadSummary(){
    
            Excel::create('records', function($excel) {
    
                $excel->sheet('Sheet1', function($sheet) {
                    $employees = Employee::all();
    
                    $arr =array();
                    foreach($employees as $employee) {
                        foreach($employee->sims as $sim){
                            $data =  array($employee->id, $employee->name, $employee->nic, $employee->address, $employee->title,
                                $sim->id, $sim->msisdn, $sim->imei, $sim->issued_to);
                            array_push($arr, $data);
                        }
                    }
    
                    //set the titles
                    $sheet->fromArray($arr,null,'A1',false,false)->prependRow(array(
                            'Employee Id', 'Employee Name', 'Employee NIC', 'Employee Address', 'Employee Title',
                            'Sim Id', 'Sim MSISDN', 'IMEI', 'Issued To'
                        )
    
                    );
    
                });
    
            })->export('xls');
        }