1

I have three tables: customers, orders and books. Orders store customers id and books store orders id.

To list orders item on customer page, I add this method to customer model:

public function customerOrders()
{
    return $this->hasMany('App\Order', 'id_customer');
}

Works fine.

Now I need to grab books for each order. So I add this method to order model:

public function orderBooks()
{
    return $this->hasMany('App\OrderBooks', 'id_order');
}

When I try to get orderBooks info inside a loop:

@foreach($customer->customerOrders as $order)
...
{{ $order->orderBooks->id }}
...

Laravel return

Property [id] does not exist on this collection instance.

How I'm sending data to view:

return view('register.customers.show', compact('customer'));

Migrations:

Schema::create('customers', function (Blueprint $table) {
    $table->increments('id');
    $table->timestamps();
});

Schema::create('orders', function (Blueprint $table) {
    $table->increments('id');
    $table->unsignedInteger('id_customer')->nullable();
    $table->foreign('id_customer')->references('id')->on('customers')->onDelete('set null');
    $table->timestamps();
});

Schema::create('books', function (Blueprint $table) {
    $table->increments('id');
    $table->unsignedInteger('id_order')->nullable();
    $table->foreign('id_order')->references('id')->on('orders')->onDelete('set null');
    $table->timestamps();
});
2
  • Can you post your migrations so we can double check this against your database layout? Commented Feb 5, 2019 at 20:12
  • See @Pourbahrami's solution below. That would be my recommendation. Commented Feb 5, 2019 at 20:35

2 Answers 2

3

try this:

@foreach($customer->customerOrders as $order)
    @foreach($order->orderBooks as $book)
        {{ $book->id }}
    @endif
@endif
Sign up to request clarification or add additional context in comments.

Comments

0

This error:

Property [id] does not exist on this collection instance.

is happening because you're trying to get a id from a collection, you want the id from the objects inside the collection

Try this instead:


@foreach($customer->customerOrders->orderBooks as $book)
{{ $book->id }}
@endforeach

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.