Default Eloquent Model Values

LaravelPosted on

It’s often the case we want to create a model instance with default values that are added automatically. Let’s see how to append default values to Eloquent models.

Laravel offers a nice way to add default values when we create a new model instance. It can be very useful and also it keeps our code a bit cleaner since we don’t need to pass extra parameters to the constructor but it appends the values automatically.

Using the $attributes the property we can define and assign the default values to the model properties.

class Post extends Model
{
    $attributes = [
        'meta' => '[]',
        'is_published' => true,
    ];

    $casts = [
        'meta' => 'array',
        'is_published' => 'boolean',
    ];
}

Now, when we create a new model like new Post, the meta attribute is not null but an empty array. In certain scenarios when we need to use the model values whether it’s saved in the database or not, this approach can be our friend.

Need a web developer? Maybe we can help, get in touch!

Similar Posts

More content in Laravel category