Search code examples
laravellaravel-mail

Why giving undefined variable in sending Email attachment in Laravel?


I can't pass any variable to Email body from Controller. I have searched many solutions but no is matching with me.

I am using Mailable. But it is empty. I am not sure it is creating problem or not.

public function __construct(){}

public function build(){}

I have tested with dummy Email without passing variable. Email is sending successfully. So, I think there is no problem with configuration.

Function in controller:

public function mail()
{
    $info = Invoice::find(65)->first();
    // 65 is giving me value. I have checked with dd()
    $data = [
        'invoice' => $info->invoiceNumber
    ];

    Mail::send(['text'=>'invoice.test'], $data, function($message) use($data){
    $pdf = PDF::loadView('invoice.test');
    $message->to('[email protected]','John Smith')->subject('Send Mail from Laravel');
    $message->from('[email protected]','The Sender');
    $message->attachData($pdf->output(), 'Invoice.pdf');
   });

   return 'Email was sent';
}

test.blade.php

<h1>It is working!! {{ $invoice }}</h1>

Data sending style is followed by: Laravel Mail::send how to pass data to mail View


Solution

  • Try adding the $data with the PDF view:

    $pdf = PDF::loadView('invoice.test', $data);
    

    But if you want to add an email body content different with the PDF content, try this:

    Mail::send([], $data, function($message) use($data){
       $pdf = PDF::loadView('invoice.test', $data);
       $message->to('[email protected]','John Smith')->subject('Send Mail from Laravel');
       $message->from('[email protected]','The Sender');
       $message->setBody('sample mail content');
       $message->attachData($pdf->output(), 'Invoice.pdf');
    });