Laravel - Mail::send() 如何将数据(以数组格式)传递到电子邮件 html 并发送

Laravel - Mail::send() How to pass data (in array format) to email html and send it

我试图在发送前将存储为数组的请求值传递给 html 格式的电子邮件。

$data = array('email' => $request->get('email'), 'name' => $request->get('name'));
    Mail::send('emails.email', ['data' => $data], function ($message) use ($data) {
        $message->subject('Hello world!');
        $message->to($data['email'], $data['name']);
    });

这是我在email.blade.php

中的电子邮件html格式文件
<h2>HELLO YOU HAVE A NEW EVENT!</h2>
<h3>TO {{$name}}</h3>
<h4>See more details .... <a href="http://localhost:8000/event" target="_blank">Events</a></h4>

但是 html 文件似乎没有收到发送的变量 ($name)

如何将数据(数组格式)传递到电子邮件html?

我尝试在没有 $ name 变量的情况下发送。看起来没有问题。一切顺利但我真的需要使用变量请帮助我

如果使用此代码,我可以使用 $name

$data['name'] = "Guest";
    Mail::send('emails.email', $data, function ($message) {
        $message->to('email@gmail.com', 'name')
                ->subject('topic');
    });

为什么?

首先,您必须在邮件中声明变量 class,如下所示:

<?php

namespace App\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;

class MailForm extends Mailable
{
    use Queueable, SerializesModels;
    public $fullname;
    /**
     * Create a new message instance.
     *
     * @return void
     */
    public function __construct($fullname)
    {
        //
        $this->fullname     = $fullname;

    }

    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
        return $this->view('sendmail');
    }
}

然后在您的视图中,您现在可以调用变量

{{ $fullname }}

不要忘记在您的控制器中调用邮件 class 和邮件外观:

use App\Mail\MailForm;
use Illuminate\Support\Facades\Mail;
Mail::send('emails.email', ['data' => $data], function ($message) use ($data) {
        $message->subject('Hello world!');
        $message->to($data['email'], $data['name']);
});

您传递的是 data 变量,而不是 name (['data' => $data])。所以从该数组中获取名称:

<h2>HELLO YOU HAVE A NEW EVENT!</h2>
<h3>TO {{ $data['name'] }}</h3>

或者直接传递 $data 变量,这样您就可以将其所有值作为单独的变量访问:

Mail::send('emails.email', $data, function ($message) use ($data) {
        $message->subject('Hello world!');
        $message->to($data['email'], $data['name']);
});