Search code examples
phplaravel-5crondompdf

Cron job in Laravel 5.6 to send email with a generated PDF file


I have a question about how to method. I'm using Laravel The goal : Send an email the last day of month with a generated PDF.

How can you do to achieve this ?

I create my PDF in controller like this (with laravel-dompdf package)

$pdf = PDF::loadView('exportPDF.templatePDF', compact('data'));
return $pdf->stream('fileName'.pdf');

Should I use a notification file (php artisan make:notification ActionNotification) to add in my job queue ? A command file (php artisan make:command ActionCmd) ? Directly in the method in my Controller ? or other method ?

I'll appreciate that you give me the right way to develop this feature in Laravel. Because I don't know how and where to start to do this.

Thank you very much.


Solution

  • You can create a Queued Job and call it via Task Scheduling. Like so:

    php artisan make:job SendMonthlyEmailWithPDF
    

    Then edit the handle method in the created class to send the email. And to call it at every end of a month:

    $schedule->job(new SendMonthlyEmailWithPDF)->when(function () {
        return \Carbon\Carbon::now()->endOfMonth()->isToday();
    });