How to set the default value of an attribute on a Laravel model

PhpLaravelLaravel 5

Php Problem Overview


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?

Php Solutions


Solution 1 - Php

Solution 2 - Php

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

Solution 3 - Php

You should set default values in migrations:

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionZeeshan Bin IqbalView Question on Stackoverflow
Solution 1 - PhpManishView Answer on Stackoverflow
Solution 2 - Phpparker_codesView Answer on Stackoverflow
Solution 3 - PhpAlexey MezeninView Answer on Stackoverflow