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!

Like our articles?
Check out our Laravel online courses!

LEAVE A REPLY

Please enter your comment!
Please enter your name here