Sometimes your project needs to set default values to some fields if it’s not set from the form/another source. In Larvel there are two ways to set default values to the DB column.
1) Database Migrations
Database migrations are an ideal solution to set default values in a DB field – probably most correct. So you don’t need to worry ever, even if you don’t send these values to your insert/update queries.
Schema::table('users', function ($table) { $table->string('status')->default('active'); });
2) Using Model Attribute
Another way of doing this is using the model attribute variable – you can add the default attribute value in the array.
class User extends Model { protected $attributes = [ 'status' => 'active' ]; }
This will take care of the default value even if you forget in the first place.
Related Articles
- Laravel 8 – Ajax File Upload with Progress Bar
- Laravel 8 Create Custom Helper Functions (Global function)
- Force HTTPS with a Middleware in Laravel
Leave a Reply