How to set the default value of an attribute on a

2019-03-22 12:51发布

This question already has an answer here:

How to set the default value of an attribute on a Laravel model?

Should I set the default when creating a migration or should I set it in the model class?

3条回答
smile是对你的礼貌
2楼-- · 2019-03-22 13:24

You can set Default attribute in Model also>

protected $attributes = [
        'status' => self::STATUS_UNCONFIRMED,
        'role_id' => self::ROLE_PUBLISHER,
    ];

You can find the details in these links

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

2.) https://laracasts.com/index.php/discuss/channels/eloquent/eloquent-help-generating-attribute-values-before-creating-record


You can also Use Accessors & Mutators for this You can find the details in the Laravel documentation 1.) https://laravel.com/docs/4.2/eloquent#accessors-and-mutators

2.) https://scotch.io/tutorials/automatically-format-laravel-database-fields-with-accessors-and-mutators

3.) Universal accessors and mutators in Laravel 4

查看更多
贪生不怕死
3楼-- · 2019-03-22 13:36

The other answers are not working for me - they may be outdated. This is what I used as my solution for auto setting an attribute:

/**
 * The "booting" method of the model.
 *
 * @return void
 */
protected static function boot()
{
    parent::boot();

    // auto-sets values on creation
    static::creating(function ($query) {
        $query->is_voicemail = $query->is_voicemail ?? true;
    });
}
查看更多
看我几分像从前
4楼-- · 2019-03-22 13:46

You should set default values in migrations:

$table->tinyInteger('role')->default(1);
查看更多
登录 后发表回答