Reputation: 2794
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();
});
Upvotes: 1
Views: 68
Reputation: 2636
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
Upvotes: 0
Reputation: 320
try this:
@foreach($customer->customerOrders as $order)
@foreach($order->orderBooks as $book)
{{ $book->id }}
@endif
@endif
Upvotes: 3