Add Default Column Value to Tables in Laravel
There may be columns in the table, for which a default value is required. When creating a record, the field may be updated later, based on some other actions, or the input fields that are optional for the user to update but need some value to display.
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, without having to write any laravel code in your model. It is automatically set and taken care of, by the database.
Schema::create('users', function (Blueprint $table) {
$table->integer('is_author')->default(0);
});
I personally find the second approach as more convenient. Of course, you can go with any of it :)