Reputation: 220
I'm sending a mail, and the view comes from the database:
$blade_from_db = 'Hello, {{ $something }}!';
$email_data = ['something' => 'World!'];
Mail::send($blade_from_db, $email_data, function ($message) use ($sender)
{
$message->from($sender->from, $sender->from_safe);
$message->to($sender->to, $sender->safe);
$message->subject($sender->subject);
});
and this is the error message:
"message": "View [Hello, {{ $something }}!] not found.",
someone can help me or give me a suggestion, since I need the content of the view to come from a database.
Upvotes: 1
Views: 5182
Reputation: 15951
$blade_from_db = view('your view',['something' => 'World!'])->render();
Mail::send([], $email_data, function ($message) use ($sender, $blade_from_db)
{
$message->from($sender->from, $sender->from_safe);
$message->to($sender->to, $sender->safe);
$message->subject($sender->subject);
$message->setBody($blade_from_db,'text/html');
});
Use $message->setBody($blade_from_db,'text/html');
to send the email with a template from database.
Hope this helps
EDIT
For Getting template from your database here is a snippet that I used in my code.
<?php
class EmailTemplate extends Model
{
use SoftDeletes;
public $table = 'email_templates';
protected $dates = ['deleted_at'];
public $fillable = [
'name',
'subject',
'content',
'variables'
];
/**
* The attributes that should be casted to native types.
*
* @var array
*/
protected $casts = [
'name' => 'string',
'subject' => 'string',
'content' => 'string'
];
/**
* Validation rules
*
* @var array
*/
public static $rules = [
// 'name' => 'required',
'subject' => 'required'
];
public function parse($data)
{
$parsed = preg_replace_callback('/{{(.*?)}}/', function ($matches) use ($data) {
list($shortCode, $index) = $matches;
if (isset($data[$index])) {
return $data[$index];
} else {
// throw new Exception("Shortcode {$shortCode} not found in template id {$this->id}", 1);
}
}, $this->content);
return $parsed;
}
}
Now in your controller, you can
$data = ['something' => 'World!'];
Mail::queue([], [], function ($m) use ($sender, $data) {
$emailTemplate = EmailTemplate::where('name', '=', 'yourtemplate')->first();
$message->from($sender->from, $sender->from_safe);
$message->to($sender->to, $sender->safe);
$message->subject($sender->subject);
$message->setBody($emailTemplate->parse($data), 'text/html');;
});
Now you can use {{something}}
in your database to populate these entries
Upvotes: 4