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

acquaintsoft logo
Acquaint Softtech

Hire Laravel developers with AI expertise at $20/hr. Get started in 48 hours.

Visit Acquaint Softtech

The latest

View all →
Validate and Convert HEIC Images in Laravel image

Validate and Convert HEIC Images in Laravel

Read article
Saga Lara Flow: Durable Workflows and Compensating Transactions on Laravel Queues image

Saga Lara Flow: Durable Workflows and Compensating Transactions on Laravel Queues

Read article
Reject Unexpected Array Keys with Laravel Validation image

Reject Unexpected Array Keys with Laravel Validation

Read article
Major performance improvements & security patches for Filament v4.12 and v5.7! image

Major performance improvements & security patches for Filament v4.12 and v5.7!

Read article
Laravel Boost Project Rules: Teach Agents Your Conventions image

Laravel Boost Project Rules: Teach Agents Your Conventions

Read article
Extract an Image's Dominant Color in Laravel image

Extract an Image's Dominant Color in Laravel

Read article