News

Attach PDFs Directly to Mailables in laravel-pdf 2.6.0

Published
Attach PDFs Directly to Mailables in laravel-pdf 2.6.0 image

Spatie's laravel-pdf v2.6.0 adds the Attachable contract support to PdfBuilder, so you can pass a generated PDF directly to attach() in a mailable or notification without saving it to disk first.

PdfBuilder now implements Illuminate\Contracts\Mail\Attachable, which means any PdfBuilder instance works wherever Laravel expects an attachable. The filename comes from name() (the .pdf extension is appended automatically if missing) and the MIME type is set to application/pdf automatically.

Here's how it looks in a notification:

use Illuminate\Notifications\Messages\MailMessage;
use Spatie\LaravelPdf\Facades\Pdf;
 
public function toMail(object $notifiable): MailMessage
{
$pdf = Pdf::view('pdfs.invoice', ['invoice' => $this->invoice])
->name('invoice.pdf');
 
return (new MailMessage)
->subject('Your invoice')
->line('Please find your invoice attached.')
->attach($pdf);
}

And in a mailable via attachments():

use Illuminate\Mail\Mailable;
use Spatie\LaravelPdf\Facades\Pdf;
 
class InvoiceMail extends Mailable
{
public function __construct(public Invoice $invoice) {}
 
public function attachments(): array
{
return [
Pdf::view('pdfs.invoice', ['invoice' => $this->invoice])
->name('invoice.pdf'),
];
}
}

References

Paul Redmond photo

Staff writer at Laravel News. Full stack web developer and author.

Filed in

Sponsored

laravelcloud logo
Laravel Cloud

Easily create and manage your servers and deploy your Laravel applications in seconds.

Visit Laravel Cloud

The latest

View all →
CPX: The Composer Package Executor for PHP image

CPX: The Composer Package Executor for PHP

Read article
Laravel AI SDK Adds Human-in-the-Loop Tool Approval image

Laravel AI SDK Adds Human-in-the-Loop Tool Approval

Read article
Pest 5 Released With Test Impact Analysis, Agent Verification, and Evals image

Pest 5 Released With Test Impact Analysis, Agent Verification, and Evals

Read article
Queue-SQL: Run Mass Deletes and Updates Across Parallel Queue Jobs image

Queue-SQL: Run Mass Deletes and Updates Across Parallel Queue Jobs

Read article
Blade Formatting in Laravel Pint image

Blade Formatting in Laravel Pint

Read article
Inertia DevTools Is Now on the Chrome Web Store image

Inertia DevTools Is Now on the Chrome Web Store

Read article