I have a Lumen (8) model with a relationship that is dependent on another relationship. I want to be able to do the following,
public function getThingId(): int
{
return $this->thing->id;
}
public function thing(): BelongsTo
{
return $this->belongsTo(Thing::class);
}
public function otherThing(): HasMany
{
return $this->hasMany(OtherThing::class, 'another_id')->where('thing_id', '=', $this->getThingId())->where(/* some more criteria */);
}
This does not work. $this->getThingId() returns null in the otherThings relationship. If I use $this->thing->id everything works. I would prefer, however, to use $this->getThingId().
Is there a way to force Laravel to load the thing relationship prior to the otherThing relationship? (or maybe there is something else going that I'm not picking up on).
You can force the eager loading of the thing relationship before accessing
getThingId()by using theloadmethod. Here's how you can modify yourotherThingrelationship to ensure that the thing relationship is loaded: