MattB
1 week ago
116
4
Laravel

Trying to get property 'name' of non-object

Posted 1 week ago by MattB

So, I have a pivot table connecting 2 other tables together. I'm trying to access the property of NAME through that table but I'm getting the "Trying to get property 'name' of non-object" error. I think it might be something to do with the relationships but I could be wrong?

View:

 @if($orderItems)
        <table class="table table-hover table-bordered" id="usersTable">
            <thead>
            <tr>
                <th>id</th>
                <th>SKU</th>
                <th>Product</th>
                <th>Price</th>
            </tr>
            </thead>
            <tbody>
            @foreach($orderItems as $item)
                <tr>
                    <td>{{$item->id}}</td>
                    <td>{{$item->product_id}}</td>
                    <td>{{$item->product->name}}</td>
                    <td>£{{$item->price}}</td>
                </tr>
            @endforeach
            </tbody>
        </table>
        {{ $orderItems->links() }}
    @endif

Controller:

public function show($id)
    {
        $orderItems = CartItem::where('admin_order_id', $id)->paginate(5);
        return view('admin.orders.show', compact('orderItems'));
    }

Model

class CartItem extends Model
{
    public function AdminOrders(){
      return $this->belongsTo('App\AdminOrders', 'admin_order_id');
    }
    public function Products(){
      return $this->belongsTo('App\Products', 'product_id');
    }
}

Migration:

public function up()
    {
        Schema::create('cart_items', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->integer('admin_order_id');
            $table->integer('product_id');
            $table->integer('price');
            $table->timestamps();
        });
    }

Please sign in or create an account to participate in this conversation.