Undefined property: Illuminate\\Database\\Eloquent\\Collection:: Laravel 5.2

瘦欲@ 提交于 2019-12-02 01:39:57

Like your error states:

Undefined property: Illuminate\Database\Eloquent\Collection::$productName

You are trying to access a property on a Collection, instead of a Model. First, you can make use of the relationship you created, like so:

$order = App\westcoorder::where('id', $orderNumber)->with('westcoorderitem')->firstOrFail();

This will ensure the order items will be included with the result, instead of executing another query to fetch them.

You can then pass on the $order to the view:

return view('welcome', compact('orderNumber', 'order'));

(You can probably just leave out the orderNumber which was the actual order, as well)

Then you can access the order in your view and loop through the items like this:

@foreach($order->westcoorderitem as $item)
    {{ $item->productName }}
@endforeach

FK

Another tip could be to update your table to use indexes to improve performance and make it neat, like the FK you mention in the comment of your create migration. You can make a migration to update it, like:

$table->foreign('westcoorder_id')->references('id')->on('westcoorders');

And/or expand on this, according to your needs (cascading, etc).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!