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
How to set the default value of an attribute on a Laravel model
提问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
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?
1.)如何为 Laravel / Eloquent 模型设置默认属性值?
You can also Use Accessors & Mutatorsfor this You can find the details in the Laravel documentation 1.) https://laravel.com/docs/4.2/eloquent#accessors-and-mutators
您也可以为此使用访问器和修改器您可以在 Laravel 文档中找到详细信息 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
2.) https://scotch.io/tutorials/automatically-format-laravel-database-fields-with-accessors-and-mutators
回答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;
});
}