Add Default Column Value to Tables in Laravel
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 🙂
Thanks bro
The second approach give the field value (in the database) a default value. The first approach only applies while in the eloquent model. I will only use the second approach as I may not always access the database through the eloquent model.
Thank You
Very Help full. My problem has been solved Now. Thanks for this solution.
Very help ful