BlackLotus
BlackLotus

Reputation: 573

How to get relationship inside a relationship

I want to get the relationship inside a relationship using Laravel eloquent relationship.

Here what i tried: This is my Order Model

public function orderProduct()
{
    return $this->hasMany(OrderProduct::class);
}

And this is my OrderProduct Model

public function expiry()
{
    return $this->hasOne(ProductExpiryDate::class);
}

I tried to get the expiry date from the main Order Model like this

$deliveryOrder = Order::find($id);
dd($deliveryOrder->orderProduct()->expiry)

And it return me an error:

Undefined property: Illuminate\Database\Eloquent\Relations\HasMany::$expiry

Please help me. Thanks.

Upvotes: 0

Views: 75

Answers (2)

Christos Papoulas
Christos Papoulas

Reputation: 2578

What you try to do is to get a relationship with its sub-relationships.

This is easy to be done with the following:

App\Order::with('OrderProduct.expiry')->get();

From the Laravel documentation you can find the following regarding the Nested Eager Loading :

To eager load nested relationships, you may use "dot" syntax. For example, let's eager load all of the book's authors and all of the author's personal contacts in one Eloquent statement:

$books = App\Book::with('author.contacts')->get();

Upvotes: 1

FULL STACK DEV
FULL STACK DEV

Reputation: 15971

You are getting this error because this is not an eager loading I would recommend

$deliveryOrder = Order::with('OrderProduct.expiry')->find($id);
dd($deliveryOrder->orderProduct->expiry)

And also when you use

$deliveryOrder->orderProduct() // this refers to relationship so 

change it to this.

$deliveryOrder->orderProduct->expiry

Hope this helps

Upvotes: 0

Related Questions