Two ways to set default DB column values in Laravel

Sometimes there is a need to set a default column value for database field - if it's not provided when creating the entry. There are two simple ways of doing it. 1. Database migrations Of course, you can set that up on the database level, which is probably the most correct - then you don't depend on Laravel code at all, database takes care of it for you. That's how you write a field migration:
Schema::table('users', function ($table) {
    $table->string('email')->default('admin@admin.com');
});
2. Model attribute Another way of doing this is in your Laravel models - you can add attributes and set default values there:
class Country extends Model {
    protected $attributes = [
        'currency' => 'USD'
    ];
}
So choose your own way, hope that's helpful!

No comments or questions yet...

Like our articles?

Become a Premium Member for $129/year or $29/month
What else you will get:
  • 58 courses (1054 lessons, total 46 h 42 min)
  • 78 long-form tutorials (one new every week)
  • access to project repositories
  • access to private Discord

Recent Premium Tutorials