Laravel 9 - Generate PDF And Attach To Email Tutorial

Apr 16, 2022 . Admin

Hi Guys,

Hello all! In this article, we will talk about laravel 9 generate PDF and attach to email example. I’m going to show you about how to generate PDF and attach to email example in laravel 9. I would like to show you laravel 9 pdf with attach to email. Here you will learn laravel 9 pdf.

In this article I’m going to share how to generate PDF and attach it to the email.

I will give you step by step implementation of how to use laravel 9 generate PDF and attach to email example.So let's follow bellow step.

Step 1: Download Laravel

Let us begin the tutorial by installing a new laravel application. if you have already created the project, then skip following step.

composer create-project laravel/laravel example-app
Step 2: 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:

Step 3: Create Controller

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

php artisan make:controller TestController    

namespace App\Http\Controllers;

use PDF;
use Mail;

class TestController extends Controller
     * Write code on Method
     * @return response()
    public function sendMailWithPDF()
        $data["email"] = "";
        $data["title"] = "Welcome to";
        $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');
Step 4: Create Blade File

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>
    <title>Laravel 9 Generate PDF And Attach To Email Example -</title>
    <h3>{{ $title }}</h3>
    <p>{{ $body }}</p>

Step 5: Create Route routes/web.php

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

| Web Routes
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!

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

All steps have been done, now you have to type the given command and hit enter to run the laravel app:

php artisan serve

Now, you have to open web browser, type the given URL and view the app output:


I Hope it will help you..

#Laravel 9