Search code examples
laravellaravel-excel

How to export only today's records in Laravel Excel


i want to export only today's record from my table not whole data, i used Carbon also it didnt work and it just simply export empty excel file. here i am sharing my code snap please help me. i am using laravel 7 and latest version of laravel-Excel package.

   <?php

namespace App\Exports;

use App\CosQueue;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;
use Maatwebsite\Excel\Concerns\WithStyles;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithEvents;
use Maatwebsite\Excel\Events\AfterSheet;
use Carbon\Carbon;
class CosQueueExport implements FromCollection, WithHeadings, ShouldAutoSize, WithEvents
{
    /**
    * @return \Illuminate\Support\Collection
    */
    public function collection()
    {
        $todaydate = date('Y-m-d');
        return CosQueue::get(array('full_name', 'job_title','meeting_with','subject','date'))->where('created_at',$todaydate);
        

    }

    

    public function headings():array{
        return[
            "اسم",
            'وظیفه',
            'ملاقات با',
            'موضوع',
            'تاریخ'

        ];
    }

    public function registerEvents(): array
    {

       
        return [
            AfterSheet::class    => function(AfterSheet $event) {
                $cellRange = 'A1:W1'; // All headers
                $event->sheet->getDelegate()->getStyle($cellRange)->getFont()->setSize(14);
                $event->sheet->getDelegate()->getStyle($cellRange)->getFont()->setName('calibri');
              
            },
        ];

       
    }
    
}

Solution

  • You can do one of these

    public function collection()
    {
       // Carbon::today() === today()
       return CosQueue::whereDate('created_at', Carbon::today())->get(array('full_name', 'job_title','meeting_with','subject','date'));
    }
    

    Also, you can do

    public function collection()
    {
       return CosQueue::whereDate('created_at', date('Y-m-d'))->get(array('full_name', 'job_title','meeting_with','subject','date')); 
    }