必须为可空字段定义mutator以避免类型错误

I'm building a medium-large size system with Laravel. It has approximately 120 tables and maybe 70 of them have CRUDs. I have a problem with all these CRUDS. Every time I have nullable field that isn't of string type I have to define a mutator of this kind:

public function setCollectionIdAttribute($value)
{
    $this->attributes['collection_id'] = $value ?: null;
}

public function setCompletedAtAttribute($value)
{ 
    $this->attributes['completed_at'] = $value ?: null;
}

I have to do this because in the front end the form fields aren't required so if a user doesn't fill the field the value that the backend receives are empty strings so when it tries to save this to the database type errors are thrown, so the functions I listed above check the values and set them to null.

Does Laravel provide a better way to do this? Because I have a lot of forms and its not cool having to define these functions every time I have a nullable field that isn't of string type.

I know the issue well and have encountered it many times before. For most projects, I create a Nullable trait that I apply to models. This trait looks for a $nullable property, loops over the attributes defined in that array, and set their values to null if they’re empty:

trait Nullable
{
    public function bootNullable()
    {
        static::saving(function ($model) {
            foreach ((array) $model->nullable as $key) {
                if (empty($model->getAttribute($key))) {
                    $model->attributes[$key] = null;
                }
            }
        });
    }
}

You then just apply this trait to your models and define the $nullable property:

class SomeModel extends Model
{
    use Nullable;

    protected $nullable = [
        'foo',
        'bar',
        'baz',
    ];
}