How to set default value fields on laravel?

Member

by lottie , in category: PHP Frameworks , 2 months ago

How to set default value fields on laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by domenico , 2 months ago

@lottie 

In Laravel, you can set default values for fields in your models by assigning the default value to the field in the model's $attributes property.


For example, if you have a User model and you want to set a default value for the 'status' field to 'active', you can do the following:

1
2
3
4
5
6
7
8
class User extends Model
{
    protected $fillable = ['name', 'email', 'status'];
    
    protected $attributes = [
        'status' => 'active',
    ];
}


Now, whenever a new User is created and the 'status' field is not provided, it will default to 'active'.


You can also set default values for fields in your database schema using migrations. For example, if you want the 'status' field in the users table to have a default value of 'active', you can do the following in your migration file:

1
2
3
4
5
6
Schema::create('users', function (Blueprint $table) {
    $table->string('name');
    $table->string('email');
    $table->string('status')->default('active');
    $table->timestamps();
});


With these configurations in place, your 'status' field will default to 'active' both in the model and in the database.