本文介绍了如何在 Laravel 模型上设置属性的默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

推荐答案

您也可以在 Model 中设置 Default 属性>

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.) 如何为 Laravel/Eloquent 模型设置默认属性值?

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

您还可以使用 Accessors &用于此的突变器您可以在 Laravel 文档中找到详细信息1.) https://laravel.com/docs/4.2/eloquent#accessors-and-mutators

You can also Use Accessors & Mutators for thisYou can find the details in the Laravel documentation1.) 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 中的通用访问器和修改器

这篇关于如何在 Laravel 模型上设置属性的默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 18:37