Skip to main content
Quick Tip

Set Default DB Column Values in Eloquent Model

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

Enjoyed This Tip?

Get access to all premium tutorials, video and text courses, and exclusive Laravel resources. Join our community of 10,000+ developers.

Recent Courses

How to Build Laravel 12 API From Scratch

28 lessons
1 h 21 min

Filament 4 From Scratch

28 lessons
2 h 25 min

PhpStorm Junie AI for Laravel Projects: Crash Course

7 lessons
36 min

We'd Love Your Feedback

Tell us what you like or what we can improve

Feel free to share anything you like or dislike about this page or the platform in general.