Laravel Generate PDF and Attach to Email

Hello artisans, in this article I’m going to share how to generate PDF and attach it to the email. I’m testing on Laravel 8.9.0. Let’s get started:

Table of Contents

  1. Install Laravel and Basic Configurations
  2. Install Package & Config
  3. Create Controller
  4. Create PDF View
  5. Define Routes

Install Laravel and Basic Configurations

Each Laravel project needs this thing. That’s why I have written an article on this topic. Please see this part from here: Install Laravel and Basic Configurations.

Install Package & Config

At first we need to install barryvdh/laravel-dompdf package. Run this composer command to install the package:

composer require barryvdh/laravel-dompdf

Now open .env file and set your SMTP credentials:


Create Controller

Create a test controller and make a function to send email:


namespace App\Http\Controllers;

use PDF;
use Mail;

class TestController extends Controller

    public function sendMailWithPDF()
        $data["email"] = "[email protected]";
        $data["title"] = "Welcome to MyNotePaper";
        $data["body"] = "This is the email body.";

        $pdf = PDF::loadView('mail', $data);

        Mail::send('mail', $data, function ($message) use ($data, $pdf) {
            $message->to($data["email"], $data["email"])
                ->attachData($pdf->output(), "test.pdf");

        dd('Email has been sent successfully');

Create PDF View

Now we’ll create the PDF view which will be attached to the email. Go to resources>views folder and create mail.blade.php file. Then paste this simple PDF view:

<!DOCTYPE html>

<h3>{{ $title }}</h3>
<p>{{ $body }}</p>


Define Routes

Open routes/web.php file and add following route:

use App\Http\Controllers\TestController;
use Illuminate\Support\Facades\Route;

Route::get('send-email', [TestController::class, 'sendMailWithPDF']);

Now run the project:

php artisan serve

Visit the send email route:


The output:

The tutorial is over. Thanks for reading.