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

2022-08-30 07:53:36

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

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


答案 1

您也可以在模型中设置默认属性>

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

您可以在这些链接中找到详细信息

1.) 如何为Laravel / Eloquent模型设置默认属性值?

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


您还可以为此使用访问器和突变体 您可以在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

3.) Laravel 4 中的通用访问器和突变体


答案 2

其他答案对我不起作用 - 它们可能已经过时了。这就是我用来自动设置属性的解决方案:

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

推荐