我正在尝试在Laravel项目中发送测试电子邮件,并遇到以下错误:
helpers.php第532行中的ErrorException:
htmlspecialchars()期望参数1为字符串,给定对象(查看:C:\ ... \ resources \ views \ mail-test.blade.php)
我一直在玩我的代码,尽我所能在网上遵循一些指导/教程,但我不知道我做错了什么。代码片段如下:
web.php
Route::post('/send-mail', 'MailController@send')->name('send-mail');
样品page.blade.php
...
<div style="text-align: center;">
<form action="{{ route('send-mail') }}" method="post">
{{ csrf_field() }}
<input type="email" name="email" placeholder="Email Address">
<input type="text" name="message" placeholder="Insert Message Here.">
<button type="submit">Let's send an email!</button>
</form>
</div>
....
MailController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Mail\Mailer;
use App\Mail\SendMail;
class MailController extends Controller
{
public function send(Request $request, Mailer $mailer) {
$mailer
->to($request->input('email'))
->send(new SendMail($request->input('message')));
return back();
}
}
SendMail.php
...
use Queueable, SerializesModels;
public $message;
/**
* Create a new message instance.
*
* @return void
*/
public function __construct($message)
{
$this->message = $message;
}
/**
* Build the message.
*
* @return $this
*/
public function build()
{
return $this->from('test@test.com')
->view('mail-test');
}
邮件-test.blade.php
<!DOCTYPE html>
<html>
<head>
<title>Email Test</title>
</head>
<body>
<h1>EMAIL TESTING</h1>
<p>{{ $message }}</p>
</body>
</html>
答案 0 :(得分:2)
Laravel会自动将$message
变量传递给视图,它是Illuminate/Mail/Message
类的一个实例。如果您需要传递给视图的内容字符串,则应在view()调用中执行此操作。但是您应该从$message
重命名它以避免冲突。我相信这可能会为你做到:
<强> SendMail.php 强>
return $this->from('test@test.com')
->view('mail-test', ['contentMessage' => $this->message]);
邮件-test.blade.php 强>
<body>
<h1>EMAIL TESTING</h1>
<p>{{ $contentMessage }}</p>
</body>