我正在尝试在浏览器中预览Mailables但我收到此错误。
Object of class App\Mail\ExamNotification could not be converted to string
我按照https://laravel.com/docs/master/mail中的所有说明操作,但找不到导致此错误的原因。
这是我的路线档案
Route::get('/mailable', function () {
$parent = App\Parents::find(2);
return new App\Mail\ExamNotification($parent);
});
以下是App \ Mail \ ExamNotification.php文件的内容
<?php
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;
use App\Parents;
class ExamNotification extends Mailable
{
use Queueable, SerializesModels;
/**
* The parent instance.
*
* @var Parent
*/
public $parent;
/**
* Create a new message instance.
*
* @return void
*/
public function __construct(Parents $parent)
{
$this->parent = $parent;
}
/**
* Build the message.
*
* @return $this
*/
public function build()
{
return $this->from('donot-replay@example.com')
->markdown('emails.exams.notification');
}
}
以下是视图文件的内容
@component('mail::message')
# Introduction
Parent Name is {{ $parent->name }}
The body of your message.
@component('mail::button', ['url' => ''])
Button Text
@endcomponent
Thanks,<br>
{{ config('app.name') }}
@endcomponent
请注意,当我在构造函数内部($ this-&gt; parent)获取正确的查询对象时。但我无法dd($ this-&gt; parent);内部构建函数(即上面提到的相同错误)。
已编辑:请注意我也可以使用此功能在路径文件
中发送邮件Mail::to('app@example.com')->send(new App\Mail\ExamNotification($parent));
所以也能够
dd(new App\Mail\ExamNotification($parent));
没有任何问题,上面的输出是
ExamNotification {#664 ▼
+parent: Parents {#687 ▶}
+from: []
+to: []
+cc: []
+bcc: []
+replyTo: []
+subject: null
#markdown: null
+view: null
+textView: null
+viewData: []
+attachments: []
+rawAttachments: []
+callbacks: []
+connection: null
+queue: null
+delay: null
}
和dd的输出($ this-&gt; parent);内部构造函数是
Parents {#687 ▼
#guard: "parent"
#table: "parents"
#dates: array:1 [▶]
#fillable: array:7 [▶]
#hidden: array:2 [▶]
#connection: "mysql"
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#attributes: array:15 [▼
"id" => 2
"name" => "James Kurian"
]
#original: array:15 [▶]
#casts: []
#dateFormat: null
#appends: []
#events: []
#observables: []
#relations: []
#touches: []
+timestamps: true
#visible: []
#guarded: array:1 [▶]
#forceDeleting: false
#rememberTokenName: "remember_token"
#forceDeleting: false
}
所以很明显,问题只在于预览邮件而不是发送邮件。
请告诉我我在哪里弄错了,并提前致谢。
答案 0 :(得分:6)
您遇到此问题的原因是因为渲染Mailables的能力仅在Laravel 5.5中引入。
您应该可以通过添加到ExamNotification
:
public function render()
{
$this->build();
if ($this->markdown) {
return $this->buildMarkdownView()['html'];
}
return view($this->buildView(), $this->buildViewData());
}
您需要更新路线以调用render()
方法:
Route::get('/mailable', function () {
$parent = App\Parents::find(2);
return (new App\Mail\ExamNotification($parent))->render();
});
我只用几个场景对它进行了测试,但似乎工作正常。