Set Default Db Column Values In Eloquent Model

Set Default Db Column Values In Eloquent Model

Quick Tips Laravel
Laravel

I have worked on several projects, and in one case I needed to set a default value for a column in one of my tables. At first, I thought it worked fine and did the job. But then I started asking myself: what if one day I need to change that default value? Of course, that would mean I’d have to modify the table migration in my database again.

From that moment, I began to wonder if there was another way to define a default value—one that could be changed anytime without touching the database migration. And it turns out, Laravel already provides us with a much more practical solution.

So If you want to set the default values for the database table column, you can do it in Migrations, using the default() method:

Schema::create('posts', function (Blueprint $table) {
    $table->id();
    $table->boolean('is_published')->default(false);
    $table->integer('view_count')->default(0);
    $table->string('status')->default('draft');
    $table->timestamps();
});

This would set the defaults on the database level.

But did you know you can also set them in the Eloquent Model, instead? Use the $attributes property for this.

app/Models/Post.php:

class Post extends Model
{
    protected $attributes = [
        'is_published' => false,
        'view_count' => 0,
        'status' => 'draft',
    ];
}

With this approach, new model instances will have these default values before they're saved. As a result, you would be able to change the default values, without changing/migrating the database structure.

Link to the Laravel docs: Eloquent: Default Attribute Values