Laravel 모델에서 속성의 기본값을 설정하려면 어떻게 해야 합니까?
마이그레이션을 작성할 때 기본값을 설정해야 합니까, 아니면 모델 클래스에서 설정해야 합니까?
질문에 대한 답변
Model에서도 Default Attribute를 설정할 수 있습니다.>
protected $attributes = [
'status' => self::STATUS_UNCONFIRMED,
'role_id' => self::ROLE_PUBLISHER,
];
자세한 내용은 다음 링크에서 확인할 수 있습니다.
1) Larabel/Allustive 모델의 기본 속성 값을 설정하려면 어떻게 해야 합니까?
2) https://laracasts.com/index.php/discuss/channels/eloquent/eloquent-help-generating-attribute-values-before-creating-record
또, 이것에 액세스와 뮤테이터를 사용할 수도 있습니다.상세한 것에 대하여는, Larabel 의 메뉴얼 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
다른 답변들은 나에게 효과가 없다 – 그것들은 구식일 수 있다.Atribute 자동설정을 위한 솔루션으로서 다음과 같이 사용했습니다.
/**
* 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;
}); }
마이그레이션에서는 기본값을 설정해야 합니다.
$table->tinyInteger('role')->default(1);