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

前端 未结 1 1604
天命终不由人
天命终不由人 2021-01-22 08:57

I\'m trying to get iot to show The items within an order and i keep getting this error

These are my models

class westcoorder extends Model
{
    protecte         


        
1条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-22 09:05

    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).

    0 讨论(0)
提交回复
热议问题