Add Default Column Value to Tables in Laravel

Laravel PHP Web Development

Some columns in the table might require default values. When creating a record, it may have some default value. The record might be updated later, based on some other actions, or the input fields.
You can use either of the described ways to set a default value for your table column while creating a new entry.

1. Model Attribute

You can set the column name in the $attribute with the field value which you want as default.

class User extends Model {
    protected $attributes = [
       'is_author' => 0,
    ];
}

Since $attribute is an array, multiple column values can be set, where the key will be the field name and value will be your default value.

2. Database Migration :

While creating the migration for the table, you can set the default property for a column. You can do this, without having to write any laravel code in your model. The database takes care of it and hence, it is automatically set.

Schema::create('users', function (Blueprint $table) {
    $table->integer('is_author')->default(0);
});

You can learn the details of laravel migration here.

I personally find the second approach as more convenient. Of course, you can go with any of it 🙂