Reputation: 14921
I have the following table structure in my database:
When I'm trying to do $this->format->product;
inside my ProductPrice
class, I get an error:
LogicException: App\ProductPrice::product must return a relationship instance.
When I perform a dd
inside my function:
dd($this->format()->first()->product);
I get the instance of the product. However, removing the dd
would still throw the exception.
Why am I getting the LogicException?
class ProductPrice extends Model
{
public function format()
{
return $this->belongsTo(ProductFormat::class, 'product_format_id');
}
public function product()
{
return $this->format->product;
}
}
class ProductFormat extends Model
{
public function product()
{
return $this->belongsTo(Product::class);
}
}
The result of dd($this->format);
returns an instance of ProductFormat
.
Upvotes: 0
Views: 234
Reputation: 14921
After investigating the HasAttributes::getRelationshipFromMethod()
, I've noticed that if the property does not exist in the properties
attribute of the class, it will try to retrieve a relation, hence the error.
To fix it, I had to add the following to my class:
protected $attributes = ['product'];
Otherwise, I could call product
as a function instead of attribute:
$price->product();
Upvotes: 1