'How to call the increment/decrement function on a nullable field | Laravel | increment | decrement function

I have an integer field, and the default value of the field is null.

Migration

Schema::table('servers', function (Blueprint $table) {
    $table->unsignedInteger('retry_ssl_renew')->nullable()->after('ssl_validity');
});

I am using Laravel's default increment-and-decrement function but because of the nullable field, the value is not changed.

When I set the default value of the field as 0, then it starts working. So is there any way we can call the increment function of Laravel on the nullable field? i.e

Schema::table('servers', function (Blueprint $table) {
    $table->unsignedInteger('retry_ssl_renew')->default(0)->after('ssl_validity');
});

Use case:- Most of my team members already create queries based on a null value, if I go with the solution(like set default as 0) then they have to change their condition. I am looking for a smart way.



Solution 1:[1]

You could for instance overwrite the increment/decrement function on your model

    protected function increment($column, $amount = 1, array $extra = [])
    {
        if ($this->getAttribute($column) === null) {
            $this->setAttribute($column, 0);
            $this->save();
        }

        return parent::increment($column, $amount, $extra);
    }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 John Zwarthoed