116

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?

1

3 Answers 3

190

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?

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


You can also Use Accessors & Mutators for this You can find the details in the Laravel documentation 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.) Universal accessors and mutators in Laravel 4

Sign up to request clarification or add additional context in comments.

7 Comments

thanks, setting default attribute works fine as protected $attributes = [ 'status' => self::STATUS_UNCONFIRMED, 'role_id' => self::ROLE_PUBLISHER, ]; but as Mutators it didn't work e.g. public function setUserTypeAttribute($value){ $this->attributes['user_type'] = 'User'; } i want to ask if there is any difference b/w these approaches, or which one is best.
Both are better. Its up to you. In mutator i gave you an example where you can set default value in case of empty or custom made condition.like public function setUserTypeAttribute($value){ $this->attributes['user_type'] = empty($value) ? 'User' : $value; } I hope you got my point with this example.
@Zeeshan Bin Iqbal Did this solve your issue?
Using a mutator won't quite work because the mutator only gets called when you assign a value to the attribute. So if you never assign a value to that attribute at all, it won't actually have the default value that you want it to.
I wish I could upvote you twice.
|
56

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

8 Comments

this is awesome
I should also specify that I try to use default values in migrations. This example above is from a Voicemail model which is extending a Recording model, so they use the same table. When a new Voicemail model is created, is_voicemail is set to true.
i just needed to set a value IF it comes through on create as null, so this worked great for me
Smartest thing I've seen on stackoverflow up to now!
|
13

You should set default values in migrations:

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

7 Comments

For example, when using models for form validation you want to have a default value before saving it to the database. When using your example, you need to add the record to the database before being able to retrieve the default value, which is cumbersome.
Not to mention that some column types don't allow defaults (such as text)
The question asks, how to set the default value on a model. It does not ask how to set the default value in the database. These are different things, and many times you may want to new a model without reference to the database
Whereas this may be the appropriate best practice for a RDBMS, the OP doesn't specify which database he is using. In a schemaless setup, this doesn't apply.
You might need to add a "->change()" to the end of this line, like this: $table->tinyInteger('role')->default(1)->change()
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.