Laravel 将参数传递给电子邮件页面

Laravel pass parameter to email page

Laravel 5 下,我正在尝试使用以下路由为用户发送邮件:

Route::post('/sendEmailToUser', array(
    'as' => 'sendEmailToUser', function () {
        $data = \App\User::find(Request::input('user_id'));
        $cdata = array('message' => Request::input('message'), 'email' => $data->email);

        Mail::send('emails.custom_email_to_user', $cdata, function ($message) use ($data) {
            $message->to($data['email'], 'Sample')->subject('Sample');
        });

        if (count(Mail::failures()) > 0) {
            Log::emergency("email dont send to user");
            return 0;
        } else {
            Log::info("email successfull send to user id" + Request::input('user_id'));
            return 1;
        }
    }
));

$cdata 的结果是:

Array
(
    [message] => this is test mail
    [email] => myname@server.com
)

不幸的是我得到了这个错误:

htmlentities() expects parameter 1 to be string, object given (View: D:\xampp\htdocs\epay-pro\resources\views\emails\custom_email_to_user.blade.php)

我的简单电子邮件页面是:

<!DOCTYPE html>
<html lang="en-US">
    <head>
        <meta charset="utf-8">
    </head>
    <body>
        <h2>Sample</h2>
        <div>
            {{$message}}
            {{ URL::to('www.epay.li') }}<br/>
        </div>
    </body>
</html>

虽然发送电子邮件 $message 变量似乎与 laravels $message 变量冲突,但我不太清楚为什么。在你的 $cdata 而不是 message 键中使用其他东西,比如 $text

$cdata = array('text' => Request::input('message'), 'email' => $data->email);

您必须在代码中更改两处,它就会起作用。

  1. 首先:(选择如何使用变量 $data)

    您使用的变量 $data 有时与 array 有时与 object 相同:

    作为对象在:

    $cdata = array('message' => Request::input('message'), 'email' => $data->email);
    

    作为数组:

    $message->to($data['email'], 'Sample')->subject('Sample');
    

    通常你应该将它用作 object 因为 User::find 将 return 一个对象。 注意:如果你想将它用作数组,你只需在find之后添加toArray()

  2. 第二个:(更改变量 $message 名称)

    Note: A $message variable is always passed to e-mail views, and allows the inline embedding of attachments. So, you should avoid passing a message variable in your view payload.

    Source : Document laravel 5.1 - mail#introduction

    因此您必须更改 $message 变量名称,因为 Framework 会将其视为 class Illuminate\Mail\Message.[=23 的对象=]

希望这对您有所帮助。