4

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?

5
  • How do you get your model, you call option values on? Laravel does not set values to null when loading relationships. Commented Apr 29, 2020 at 11:47
  • @mrhn in controller after getting the product via $product = Product::find($request->id), I call $product->load('optionValues') Commented Apr 29, 2020 at 12:20
  • You should go with query scopes for this case. Commented Apr 29, 2020 at 12:46
  • @Tpojka a little bit more clarification if it's possible? Commented Apr 29, 2020 at 12:49
  • Have you checked purpose of scopes in documentation? There you would find how to pass arbitrary (in this case request('optionValues')) parameter. Commented Apr 29, 2020 at 12:51

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.