如何使空值具有默认值



im试图在空白时给予模型属性值另一个值目前,这是我在模型中使用的内容:

public function getAttribute($property){
    if(blank($this->attributes[$property])){
        return $this->attributes[$property] = '-';
    }else{
        return $this->attributes[$property];
    }
}

它有效,但我不认为这是正确的方法。

我正在寻找一种正确的方法。

示例:

可以说数据库中的值为null,我希望它在显示时显示" - ",但我不想保存" - "在数据库中。(我也不想为每个值使用" get ... value"突变器(

解决方案1

自PHP 7以来,有一个新功能,称为NULL合并操作员。它在存在时返回第一个操作员,而不是NULL

{{ $model->attribute ?? '-' }}

与此相同:

{{ isset($model->attribute) ? $model->attribute : '-' }}

解决方案2

另一个解决方案会更难,但可行:

创建一个基本模型,您可以扩展所有其他模型:

class BaseModel extends Model {
    protected $emptyAttributes = [];
    protected function getAttribute($property)
    {
        if (in_array($property, $this->emptyAttributes) && blank($this->attributes[$property])) {
            return '-';
        }
        else {
            return $this->attributes[$property];
        }
    }
}

现在将所有想要的模型扩展到此新类,并创建一个"替换属性"的数组:

class User extends BaseModel {
    protected $emptyAttributes = ['name', 'email'];
}

这应该自动替换属性nameemail,当它们为空,null或仅空格的字符串时。

旁注:您也可以将功能移至特征(这可能是一个更优雅的解决方案,但这取决于您(。

最新更新