Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel access model's property in relation method

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?

like image 258
Hadi Sharghi Avatar asked Oct 21 '25 04:10

Hadi Sharghi


1 Answers

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.

like image 91
Hadi Sharghi Avatar answered Oct 22 '25 20:10

Hadi Sharghi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!