Sending email with laravel, but doesn't recognize variable

筅森魡賤 提交于 2019-12-12 07:09:37

问题


I'm trying to send an email through Laravel, but I'm getting this error:

Undefined variable: contactEmail

Even though it got defined above it. What is going wrong here?

Controller

$contactName = Input::get('name');
$contactEmail = Input::get('email');
$contactMessage = Input::get('message');

$data = array('name'=>$contactName, 'email'=>$contactEmail, 'message'=>$contactMessage);
Mail::send('template.mail', $data, function($message)
{   
    $message->from($contactEmail, $contactName);
    $message->to('info@aallouch.com', 'myName')->subject('Mail via aallouch.com');
});

EDIT:

template.mail

Name: {{$name}}
Email: {{$email}}
Message:{{$message}}

回答1:


As your $data variable is defined as:

$data = array(
    'name'=>$contactName, 
    'email'=>$contactEmail, 
    'message'=>$contactMessage
);

You won't have a $data available in your view, but you can use directly:

{{ $name }}
{{ $email }}
{{ $message }}

EDIT:

And your controller should have:

    $contactName = Input::get('name');
    $contactEmail = Input::get('email');
    $contactMessage = Input::get('message');

    $data = array('name'=>$contactName, 'email'=>$contactEmail, 'message'=>$contactMessage);
    Mail::send('template.mail', $data, function($message) use ($contactEmail, $contactName)
    {   
        $message->from($contactEmail, $contactName);
        $message->to('info@aallouch.com', 'myName')->subject('Mail via aallouch.com');
    });

You must pass your variables to the closure using

use ($contactEmail, $contactName)

As shown above.




回答2:


I have got this error and I have solved it. I have replace $message keyword with $comment from $data.

Example below :

$data = array('name' => 'vikas', 'message' => 'test message');

view

{{ $name }}
{{ $message }}

It's getting error

$data = array('name' => 'vikas', 'comment' => 'test message');

{{ $name }}
{{ $comment }}

Now it's working fine.




回答3:


If you look at source code you'll see this line:

 $data['message'] = $message = $this->createMessage();

So your message field is overwritten by that line. Use other name for the field like text or comment.



来源:https://stackoverflow.com/questions/19412055/sending-email-with-laravel-but-doesnt-recognize-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!