Reputation: 1005
I have a relation method for a model which has a condition based on a property of the model itself.
// ProductController.php
public function show($id, Request $request) {
$product = Product::find($id);
if ($request->exists('optionValues') {
$product->load('optionValues');
}
}
// Product.php
public function optionValues()
{
/// here $this->stock_status_id is null. actually all attributes array is empty.
if ($this->stock_status_id == Stock::CUSTOM_ORDER) {
return $this->hasMany(ProductOptionValue::class, 'product_id', 'product_id')
->where('status', 1);
}
return $this->hasMany(ProductOptionValue::class, 'product_id', 'product_id')
->where('price', '>', 0)
->where('quantity', '>', '0')
->where('status', 1);
}
but it seems when Laravel is loading a relation all properties are null.
and $this->stock_status_id
for current model is null, and I can't check for the condition.
Is there any workaround this problem?
Upvotes: 4
Views: 1117
Reputation: 1005
After 2 hours of debugging I discovered that Laravel has different way of loading relations when using $model->load('relationName')
method than calling it via $model->relationName
When using ->load('relationName')
method the instance of model has no attributes yet even when all attributes have been loaded properly before calling $model->load()
.
But when using $model->relationName
on a model instance, the instance have all the attributes present when trying to load the relation.
So, I changed this line of code
$product->load('optionValues');
to this:
$product->optionValues;
And the condition checking in the optionValues()
method, works as expected.
Upvotes: 3