如何将集合传递给可邮寄的Laravel对象

3
如何使用可发送邮件的方法(sendable)并在视图中组织集合(collection)中的创建项?
我在控制器中按以下方式创建订单(order):
$order = Order::create([
            'products' => json_encode(new CartItemCollection($items)),
            'price' => $PartialPrice,
            //other stuff
        ]);

在我的购买函数中,我发送电子邮件的方式如下:
            $pro = $order->products;
            $data = [
                'extra_address' => $order->extra_address,
                'address' => $order->address,
            ];

            Mail::to($check_user->email)->send(new NewPurch($data, $pro));

在我的电子邮件配置中,有以下内容:
public $data;
public $pro;

public function __construct($data,$pro)
{
    $this->data = $data;
    $this->pro = $pro;
}


public function build()
{
    return $this->markdown('newpurch')->with(['data' => $this->data])->subject('Thank you');
}

我已经接收到数据,但是不知道如何访问每一个数据。

@component('mail::message')

Someone want this:

{{$pro}}

@endcomponent

邮件看起来像这样: enter image description here 但我无法将其作为对象$pro->id或键$pro['id']访问。
编辑: 如果我尝试这样做:
@component('mail::message')

Someone want this:

@foreach($pro->items as $item)
  {{ $item->id }}
@endforeach

@endcomponent

出现以下错误:

尝试获取非对象的 'items' 属性 (View: /app/resources/views/newpurch.blade.php)

如果我尝试这样做:

 @component('mail::message')

<?php
$deco = json_decode($pro,true);
?>
Someone want this:
  {{ $deco }}

@endcomponent

出现以下错误:

htmlspecialchars() 函数期望参数 1 是字符串,但实际传入的是数组 (视图文件:/app/resources/views/newpurch.blade.php)

1个回答

2

编辑:

public $data;
public $pro;

public function __construct($data, $pro)
{
    $this->data = $data;
    $this->pro = json_decode($pro, true);
}


public function build()
{
    return $this->markdown('newpurch')->with(['data' => $this->data])->subject('Thank you');
}

由于我们现在回到了一个集合而不是一个字符串,因此请使用foreach。

@foreach($pro->items as $item)
  {{ $item->id }}
@endforeach


1
除非模型设置将“products”转换为集合,否则它将是一个字符串。如果它是一个字符串,首先需要将其json解码为数组或对象,然后可以对其进行迭代。 - patricus
显然我可能错了,但这是我看到的:在create()语句中,products被设置为集合的json编码表示(一个字符串)。然后,你有$pro = $order->products;,所以现在$pro是一个字符串。这个字符串被传递到NewPurch构造函数中,该构造函数设置了公共的$pro属性(仍然是一个字符串)。这个公共属性然后在视图中使用(仍然是一个字符串)。它只能在视图中成为一个集合,如果有隐藏的代码将其转换回集合,或者在模型上有一个显式的$casts设置将products转换为collection - patricus
已经尝试过这个了,但是我得到了这个错误:尝试获取非对象的属性'items'(视图:/app/resources/views/newpurch.blade.php),我认为这是由于编码问题,但不知道在哪里进行json_decode。 - Wilson Guerrero
请编辑原始问题并提供更多信息,谢谢大家。 - Wilson Guerrero
@patricus 我甚至没有看到他在解析。我以为pro是模型集合本身。我会更新我的答案。 - Michael Mano

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接