Search code examples
phpmodellaravellaravel-4eloquent

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


If I try declaring a property, like this:

public $quantity = 9;

...it doesn't work, because it is not considered an "attribute", but merely a property of the model class. Not only this, but also I am blocking access to the actually real and existent "quantity" attribute.

What should I do, then?


Solution

  • 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.