title: Attach PDF file to email with DOMPDF in Laravel
body: <p>I'm using my MyEmail model to attach a PDF file to it. The mail gets sent with all the data I want and a PDF gets attached but it is empty, how can I import my layout and data into the PDF if I attach?</p>
  <pre><code>&lt;?php
  
  namespace App\Mail;
  
  use Illuminate\Bus\Queueable;
  use Illuminate\Mail\Mailable;
  use Illuminate\Queue\SerializesModels;
  use Illuminate\Contracts\Queue\ShouldQueue;
  use App\Course;
  use Barryvdh\DomPDF\PDF;
  
  class MyEmail extends Mailable {
      use Queueable, SerializesModels;
      public $data;
      public $course;
      private $pdf;
  
      /**
       * Create a new message instance.
       *
       * @return void
       */
      public function __construct($data, Course $course) {
          $this-&gt;course = $course;
          $this-&gt;data = $data;
      }
  
      /**
       * Build the message.
       *
       * @return $this
       */
      public function build() {
          return $this-&gt;subject('Thanks')-&gt;view('emails.my_email')-&gt;attachData($this-&gt;pdf, 'my_pdf.pdf')-&gt;with(['data' =&gt; $this-&gt;data, 'course' =&gt; $this-&gt;course]);
      }
  }
  </code></pre>
  <p>Here's the function to send the email my controller:</p>
  <pre><code>public function sendMail(Request $request) {
  
      $data = array(
          'first_name'        =&gt; $request-&gt;first_name,
          'last_name'         =&gt; $request-&gt;last_name,
          'id'                =&gt; $request-&gt;id,
          'course_id'         =&gt; $request-&gt;course_id,
      );
  
      $resultJson = $this-&gt;validateRecaptcha($request);
  
      $course= Course::where('id', $data['course_id'])-&gt;first();
  
      if($resultJson-&gt;success != true) :
          return redirect()-&gt;back()-&gt;with(['success' =&gt; 'success']);
      else :
          \Mail::to($request-&gt;email)
               -&gt;cc('my@*******')
               -&gt;queue(
              new Mail\MyEmail($data, $course)
          );
          return redirect()-&gt;back()-&gt;with(['success' =&gt; 'Success!']);
      endif;
      
  }
  </code></pre>