I think the relation is not loaded by default. You can use with or load methods to eager load the relations.
Dec 20, 2022
9
Level 2
HasOneThrough() not working with Inertia?
Hello, I am facing a bit of a weird issue... I have a ProductVariant model, that has one Merchant through a Product like so:
public function merchant(): HasOneThrough
{
return $this->hasOneThrough(
Merchant::class,
Product::class,
'id',
'id'
);
}
This Merchant has a getCurrencyAttribute() method, that I can access from the ProductVariant without issues: $productVariant->merchant->currency;, and I use it to format the ProductVariant price, like this:
protected $with = [
'merchant'
];
protected $appends = [
'priceFormatted',
];
public function getPriceFormattedAttribute()
{
return "{$this->merchant->currency->symbol} {$this->price}";
}
On my controller, I am fetching the Product like this:
$product = Product::with(['merchant', 'variants'])
->where('slug', $slug)
->firstOrFail()
;
All good so far. From my controller I can do $product->variants[0]->priceFormatted and it works. But as soon as I return an Inertia render like this:
return Inertia::render('ProductPage', [
'product' => $product,
]);
I get this error:
Attempt to read property "currency" on null.
Please or to participate in this conversation.