php 如何在 Laravel 模型上设置属性的默认值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39912372/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 02:02:36  来源:igfitidea点击:

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

phplaravellaravel-5

提问by Zeeshan Bin Iqbal

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

如何在 Laravel 模型上设置属性的默认值?

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

我应该在创建迁移时设置默认值还是应该在模型类中设置它?

回答by Manish

回答by parker_codes

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;
    });
}

回答by Alexey Mezenin

You should set default values in migrations:

您应该在迁移中设置默认值:

$table->tinyInteger('role')->default(1);