Eloquent use default value if column is null

Viewed 407

I want to use the default value if the column is null. For example:

Settings (Table):

id | website_id | column1 | column2
1  |     1      |   null  |  null

Website.php:

<?php

namespace App\Models;

class Website extends Model
{
    public function Setting(): HasOne
    {
        return $this->hasOne(IvendiFinanceCalculatorSetting::class)->withDefault([
            'column1' => 'Default',
            'column2' => 0,

The above is a hypothetical example, but you can see what I'm attempting to achieve. If I add a row to my table with a matching website id, but leave the other columns as null I want to return the defaults.

Currently if query the Website model with the settings relationship I get back the row but column1 and column2 is null rather than Default and 0.

dd(Website::query()->with('Setting')->find(1));
1 Answers

withDefault works when the relationship is null, not the field values. See Null Object Pattern for more information.

You might be better served by model events, specifically creating for when new IvendiFinanceCalculatorSetting records are inserted.

Then in the model's boot method or an observer class, you can set default setting values:

// IvendiFinanceCalculatorSettingObserver.php example

public function creating (IvendiFinanceCalculatorSetting $setting) {
    $setting->setAttribute('column1', 'Default');
    $setting->setAttribute('column2', 0);
}

Another approach is setting the default values directly in the model's attribute property:

/**
 * The model's default values for attributes.
 *
 * @var array
 */
protected $attributes = [
    'column1' => 'Default',
    'column2' => 0
];
Related