How to Create Dynamic PDF & Send By Email in Laravel

Preetii Hirani

In this Article, how to create dynamic PDF and Sending PDF attached by Email in Laravel. We will help you to give example of generate PDF and send Email.

First of all we can install barryvdh/laravel-dompdf package from composer command in your Laravel application.

composer require barryvdh/laravel-dompdf


After successfully install package and open config/app.php file and add this:





            ‘PDF’ => Barryvdh\DomPDF\Facade::class



After Setting up mail server details in .env file. You have to add send mail configuration with mail driver, mail host, mail port, mail username, mail password.






After open routes/web.php and controller URL:



After create Controller file Mail_pdf.php name:

namespace App\Http\Controllers;


use Illuminate\Http\Request;

use App\Http\Controllers\Controller;

use Illuminate\Support\Facades\DB;

use Illuminate\Support\Facades\Route;

// for pdf

use Barryvdh\DomPDF\Facade as PDF;

//for mail

use Illuminate\Support\Facades\Mail;

use Illuminate\Mail\Mailable;


class Mail_pdf extends Controller {

    function index(Request $request) {

        $user = DB::table('users')



        $data['username'] = $user->username;

        $data['email'] = $user->email;

//generating pdf with user data

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


//send mail to user

        Mail::send('message', $data, function($message) use ($data, $pdf) {




            $message->attachData($pdf->output(), 'Receipt.pdf'); //attached pdf file






The output file name is Receipt.pdf and it will be attached with the Email.

Then, create blade file on resource directory. PDF view file in view folder name is user_details.blade.php



        <title>How to create Dynamic PDF & Sending by Email in Laravel</title>



        <h1>User Details:</h1>

        <p>Username: {{ $username }}</p>

        <p>Email: {{ $email }}</p>




Last one create message file for users mail. That file name is message.php in view folder.



        <title>How to create Dynamic PDF & Sending by Email in Laravel</title>




            Your Automatically Generate Receipt...







     Then what???????????????? Wheres the button, generate, attach, send commands

Leave a Comment

Your email address will not be published.

First Floor, Madhav Complex, V. R. Nagar, Mirjapar Madhapar By Pass Ring Road, Bhuj-370001
+(91) 97 26 134340
Mon-Fri 9:00am-6:00pm
24 X 7 online support