Search code examples
laravellaravel-7

Laravel excel export how to export conditional data?


I am trying to export partial data from my table not all data, I am using Maatwebsite plugin

I have tried below code in controller

public function report(Request $request)
{
       
     
        $sdate  = $request->query('sdate');
        $edate  = $request->query('edate');
       
        
       
        $report = Report::whereDate('created_at', '>=', $sdate)
                                   ->whereDate('created_at', '<=', $edate)
                                   ->get();
        

        
       return Excel::download($report, 'report.xlsx');

 }

In this time I am getting empty excel file.

I am able to get all data after creating app/export

like below

app/export/ReportExport.php

public function collection()
{
        return Report::all();
}

but how I can I do it in controller ? or how can I sent $report data controller to collection ?


Solution

  • You can use the FromQuery concern provided by the package.

    namespace App\Exports;
    
    use App\Report;
    use Maatwebsite\Excel\Concerns\FromQuery;
    use Maatwebsite\Excel\Concerns\Exportable;
    
    class ReportExport implements FromQuery
    {
        use Exportable;
    
        public function __construct($start, $end)
        {
            $this->start = $start;
            $this->end = $end;
        }
    
        public function query()
        {
            return Report::query()->whereDate('created_at', '>=', $this->start)
                                  ->whereDate('created_at', '<=', $this->end);
        }
    }
    

    Then from you controller, you can call it

    return (new ReportExport($sdate, $edate))->download('report.xlsx');
    

    I have not tested the code. So apologies if I made a mistake. You can refer to official documentation.

    There are also other methods of exporting which you can find from the documentation.