Home > OS >  How to make Laravel Mail as Traits?
How to make Laravel Mail as Traits?

Time:06-22

I try to send email but it return error Undefined variable emailData in view. I use Traits so it can simple reuse in other controller.

my Traits

trait SendEmail
{

     public function sendMail ($emailTemplate,$emailData, $emailSubject, $emailTo) {
        Mail::send($emailTemplate,  $emailData, function($message) use ($emailData, $emailSubject, $emailTo)
            {    
                $message->to($emailTo)
                ->subject($emailSubject); 
            });

        if (Mail::failures()) {
            return false;
        } else {
            return true;
        }
     }
}

Controller


$emailData = [
                    'operatorName' => $queryOperator->OPERATOR_NAME,
                    'operatorUser' => $queryOperator->USERNAME,
                    'operatorPwd' => $queryOperator->WAGWORD,
                ];
                // return $emailData['operatorName'];
                $emailTo = $queryOperator->EMAIL;
                $emailSubject = "Bakti - Operator Registration";
                $emailTemplate = 'emails.regisOperator'; // path of blade view file for email

                // return $emailTemplate;
                $emailThis = $this->sendMail($emailTemplate, $emailData, $emailSubject, $emailTo);

Email Blade

<p>{{$emailData}}</p>

the debug error message :

"message": "Undefined variable: emailData (View: \regisOperator.blade.php)",

CodePudding user response:

I think you should pass $emailData as ['emailData' => $emailData] like this:

$emailThis = $this->sendMail($emailTemplate, ['emailData' => $emailData], $emailSubject, $emailTo);```
  • Related