Home > Enterprise >  LaravelExcel Maatwebsite Does Not Export Data
LaravelExcel Maatwebsite Does Not Export Data

Time:01-18

I'm working with Laravel 5.8 and I have added LaravelExcel Maatwebsite to export some data from the DB into excel file.

So I tried adding this method to the Model:

public static function getAllData()
{
    $records = DB::table('orders')->select('ord_id','ord_date','ord_total')->get()->toArray(); 
}

And then I made this Export Class:

class OrderAllDataExport implements FromCollection, WithHeadings
{
    public function headings():array
    {
        return [
            'ID',
            'Date',
            'Total',
        ];
    }
    
    public function collection()
    {
        return collect(Order::getAllData());
    }
}

And also added this method to the Controller:

public function exportAllDataIntoExcel()
{
    return Excel::download(new OrderAllDataExport,'orders_all.xlsx');
}

And this is the route:

Route::get('export/data/list/orders' , 'OrdersController@exportAllDataIntoExcel')->name('exportAllDataIntoExcel');

But when I test this, the excel file downloaded properly but it is empty!

image capture

CodePudding user response:

Have you try putting your select query to collection to test it?

    public function collection()
    {
       $data = DB::table('orders')
                ->select('ord_id','ord_date','ord_total')
                ->get();

       return $data;
    }

also you can try add return to your getAllData()

public static function getAllData()
{
   $records = DB::table('orders')->select('ord_id','ord_date','ord_total')->get(); 
   return $records;
}

and because u use collection i removed the toArray() function

  • Related