试图在Laravel的View中获取非对象的属性

时间:2016-10-18 10:56:38

标签: php laravel

我是Laravel的新手,我认为在尝试将数据传递给视图时,我做错了。

这是我的路线,在那里我构建了一个简单的数组:

searchHtml.find(".link-title").each(function(){
  linkTitle.push($(this).text());
  console.log($(this).text());
})

以下是我在观看方面的尝试方式:

Route::get('/', function () {
    $data = [];

    foreach(App\User::all() as $user) {
        foreach($user->orders as $order) {
            foreach ($order->sub_orders as $sub_order) {
                $data[] = 
                    [
                        'customer_id' => $user->id, 
                        'customer_name' => $user->name, 
                        'city' => $user->city, 
                        'order_id' => $order->id, 
                        'order_date' => $order->created_at->format('Y-m-d H:i:s'),
                        'sub_order_id' => $sub_order->id,
                        'item_name' => $sub_order->item->name,
                        'quantity' => $sub_order->quantity,
                        'unit_price' => $sub_order->item->unit_price,
                        'total_price' => $sub_order->item->unit_price * $sub_order->quantity,
                        'delivery_date' => $sub_order->delivery_date,
                        'delivery_status' => $sub_order->delivery_status
                    ];
            }
        }
    }

    return view('welcome', ["data" => $data]);
});

这会在@foreach ($data as $row) <tr> <td> {{ $row->customer_id }} </td> </tr> @endforeach 行上显示错误Trying to get property of non-object。我不明白我做错了什么。 :|

此外,视图中收到的数据有<td> {{ $row->customer_id }} </td>dd吗?

4 个答案:

答案 0 :(得分:2)

$row是数组而不是对象。您可以通过

访问它
$row['customer_id'];

PS:是的,你可以在视图中使用print_r($data);查看它,也可以使用var_dumpdd

答案 1 :(得分:1)

$row->customer_id替换为$row['customer_id']以访问array值;

答案 2 :(得分:0)

$row是一个关联数组。你可以这样:

@foreach ($data as $row)
  <tr>
      <td> {{ $row['customer_id'] }} </td>
  </tr>
@endforeach

答案 3 :(得分:0)

$row不是一个对象,它是一个关联数组。像这样访问它

$row['customer_id'];

您可以使用dd查看数据:)