How to set a default attribute value for a Laravel / Eloquent model?

前端 未结 3 1605
醉梦人生
醉梦人生 2020-11-30 07:22

If I try declaring a property, like this:

public $quantity = 9;

...it doesn\'t work, because it is not considered an \"attribute\", but mer

3条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-30 08:00

    This is what I'm doing now:

    protected $defaults = array(
       'quantity' => 9,
    );
    
    public function __construct(array $attributes = array())
    {
        $this->setRawAttributes($this->defaults, true);
        parent::__construct($attributes);
    }
    

    I will suggest this as a PR so we don't need to declare this constructor at every Model, and can easily apply by simply declaring the $defaults array in our models...


    UPDATE:

    As pointed by cmfolio, the actual ANSWER is quite simple:

    Just override the $attributes property! Like this:

    protected $attributes = array(
       'quantity' => 9,
    );
    

    The issue was discussed here.

提交回复
热议问题