我是Laravel的初学者。我创建了联系表单功能。
我有此代码:
public function sendContactForm($request)
{
$this->validate($request, [
'name' => 'required|string',
'topic' => 'required|string',
'email' => 'required|email',
'message' => 'required|string',
'captcha' => 'required|captcha',
'acceptReg' => 'required|integer',
]);
$adminEmail = $this->frontendRepository->getSystemAdminEmail();
$title = $request->input('topic');
$txt = nl2br($request->input('message'));
$userName = $request->input('name');
$email = $request->input('email');
$ip = $request->getClientIp();
$dateTime = date('Y-m-d H:i:s');
$mailTitle = "Masz wiadomość ze strony". env('APP_NAME')."<br/>";
$message = "
<b>Dane wiadomości:</b> $dateTime [$ip]<br/>
<b>Tytuł wiadomości:</b> $title<br/>
<b>Imię:</b> $userName<br/>
<b>Adres email:</b> $email<br/>
<b>Wiadomość:</b> $txt<br/>";
Mail::to($adminEmail)->send(new ContactMail($message, $mailTitle, $email, $adminEmail));
die('mail sent!');
}
ContactMail.php
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;
class ContactMail extends Mailable
{
use Queueable, SerializesModels;
public $message;
public $title;
public $sender;
public $adminMail;
/**
* Create a new message instance.
*
* @return void
*/
public function __construct(string $message, string $title, string $sender, string $adminMail)
{
$this->message = $message;
$this->title = $title;
$this->sender = $sender;
$this->adminMail = $adminMail;
}
/**
* Build the message.
*
* @return $this
*/
public function build()
{
return $this->subject($this->title)
->from($this->sender)
->to($this->adminMail)
->replyTo($this->sender)
->view('mail.contactform', ['message' => $this->message]);
}
我的联系form.blade.php:
@section('content')
{{ $message }}
@endsection
运行脚本时出现错误:
htmlspecialchars()期望参数1为字符串,指定对象(查看:> /var/www/project/resources/views/mail/contactform.blade.php)
我该如何修理?
答案 0 :(得分:1)
build()
类的 Mailable
方法来配置邮件对象并返回self。因此,请在您的通话链末尾删除->send(..)
通话:
public function build()
{
return $this->subject($this->title)
->from($this->sender)
->to($this->adminMail)
->replyTo($this->sender)
->view('mail.contactform');
}
编辑:
htmlspecialchars()期望参数1为字符串,指定对象(查看:> /var/www/project/resources/views/mail/contactform.blade.php)
问题出在您的邮件模板文件contactform.blade.php
中-您不能在$message
类中使用变量名Mailable
,因为Laravel本身使用它来传递Mailable
对象到模板(因此模板$message
中包含对对象的引用,而不是对消息字符串的引用)。因此,您可以认为它是框架保留的。
要解决此问题,请将{{1}中的$message
字段重命名为其他内容,例如$content
(或$text
,$body
等) }类和ContactMail
。