Create a dynamic Laravel accessory

I have a model Productas well as a model Attribute. The relationship is between Productand Attributemany for many. In my model, ProductI am trying to create a dynamic accessory. I am familiar with Laravel accessories and the mutator function described here here . The problem I am facing is that I do not want to create an accessory every time I create a product attribute.

For example, a product may have a color attribute that can be configured as follows:

/**
 * Get the product color.
 *
 * @param  string  $value
 * @return string
 */
public function getColorAttribute($value)
{
    foreach ($this->productAttributes as $attribute) {
        if ($attribute->code === 'color') {
            return $attribute->pivot->value;
        }
    }

    return null;
}

After that, the color of the product can be obtained in this way $product->color. If I need to add an attribute sizeto the product, I will need to set up another accessor in the model Product, so I can access it as follows: $product->size.

"" ?

Laravel ?

+4
3

, getAttribute() Eloquent Model ( ), , , .

, :

public function getProductAttr($name)
{
    foreach ($this->productAttributes as $attribute) {
        if ($attribute->code === $name) {
            return $attribute->pivot->value;
        }
    }

    return null;
}

:

$model->getProductAttr('color');
+2

Override Magic - __ get().

.

public function __get($key)
{
    foreach ($this->productAttributes as $attribute) {
        if ($attribute->code === $key) {
            return $attribute->pivot->value;
        }
    }

    return parent::__get($key);
}
+2

, , , , .

class YourModel extends Model{

  public $code;

  public function getProductAttribute()
  {
    //a more eloquent way to get the required attribute
    if($attribute = $this->productAttributes->filter(function($attribute){
       return $attribute->code = $this->code;
    })->first()){
        return $attribute->pivot->value;
    }

    return null;
  }
}

do

$model->code = 'color';
echo $model->product;

0

Source: https://habr.com/ru/post/1689702/


All Articles