我有一个内置于laravel 4的电子邮件应用程序。我的用户需要能够在他们的电子邮件签名行中添加多个促销,但我完全不想尝试将数据导入电子邮件视图。
具体来说,我遇到的问题是我试图将一个数组$ mData发送到我的邮件视图,其中包含一组json编码对象。
我的术语可能不对,所以这是一个例子:
$mData['subject'] = 'this is a subject line';
$mData['promotion'] = [[{"id":1,"user_id":2,"path":"\/uploads\/attachments\/XDIzaf9lfcHg.jpg"},{"id":2,"user_id":2,"path":"\/uploads\/attachments\/XDIzaf9lfcHg.jpg"}]]
然后我需要在电子邮件中迭代$ mData ['promotion']来内联显示图像。我无法弄清楚如何格式化$ mData ['promotion']以便我可以遍历它。
这是我的邮件构造函数:
public function emailConstructor($subject, $body)
{
$userId = $this->user->id;
$eloquentUser = User::find($userId);
$mData['from'] = $this->user->email;
$mData['fromName']= $this->user->first_name. " ". $this->user->last_name;
$mData['subject'] = $subject;
$promotionCount = $this->emailPromotionCount($userId);
if(count($promotionCount) >= 1){
$mData['promotion'] = $promotionCount;
}
return $mData;
}
public function emailPromotionCount($userId)
{
$count = SignaturePromotion::where('user_id', '=', $userId)->get();
$promotionCount = json_encode(array($count));
return $promotionCount;
}
我的邮件程序功能很标准:
public function emailTo($view, $mData)
{
Mail::send($view, $mData, function($message) use ($mData)
{
$message->from($mData['from'], $mData['fromName']);
$message->to($mData['email'], $mData['name'])->subject($mData['subject']);
$message->getHeaders()->addTextHeader('X-MC-Metadata', $mData['meta']);
if(array_key_exists('path', $mData)){
$message->attach($mData['path'], array('as' => $mData['display']));
}
});
}
我试过用几种方法解码JSON。这是我的电子邮件刀片文件中的一个片段:
<div>
@if($promotion)
@foreach(json_decode($promotion) as $promo)
{{$promo->path}}
@endforeach
@endif
任何想法如何正确格式化$ mData ['promotion'],以便我可以在电子邮件视图中循环它?
编辑 - 回答
问题是我如何编码我的json:
$count = SignaturePromotion::where('user_id', '=', $userId)->get();
$promotionCount = json_encode(array($count));
应该是
$count = SignaturePromotion::where('user_id', '=', $userId)->get()->toJson();
不需要$ promoteCount = json_encode(array($ count));