在 MySQL 之外为 Laravel 模型字段提供默认值的正确方法是什么?

What's the correct way to provide default values for Laravel model fields outside of MySQL?

我有一个 Laravel 模型,其中有多个字段在数据库中默认为 NULL,并且由于遗留原因无法轻易更改。我希望始终 return 这些作为空字符串,例如,当 returning JSON 从我的路线返回时。是否有 "standard" 方法以某种方式在模型中定义默认值?

另一种情况可能是某个字段在被 returned 之前总是需要对其进行一些处理,这也可以用类似的方式定义吗?谢谢。

默认值

您可以使用 $attributes 属性:

指定默认值
class MyModel extends Eloquent {
    protected $attributes = array(
        'foo' => 'bar'
    );
}

但是我认为这仍然会被数据库中的 NULL 覆盖。 $attributes 的用例是在创建和插入新记录时。

操纵JSON/数组输出

要在将模型转换为 JSON / 之前更改模型,您可以覆盖模型中的 toArray()

public function toArray(){
    $array = parent::toArray();
    foreach($array as &$value){
        if($value == null){
            $value = '';
        }
    }
    return $array;
}

带有访问器的自定义属性

如果您有某些字段需要特殊类型的处理(例如格式化日期、连接两个属性),您可以使用 accessor:

public function getFullNameAttribute(){
    return $this->attributes['firstname'].' '.$this->attributes['lastname'];
}

现在您可以通过 $model->full_name(或 $model->fullName 任何您喜欢的方式访问它)

最后,要将其添加到 JSON / 数组输出,请使用 $appends

protected $appends = array('full_name');