xVivio
xVivio

Reputation: 43

How to make empty values have a default value?

Im trying to give model attribute values another value when they are blank, At the moment this is what I'm working with in my model:

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

It works, but I dont think this is the right way to do it.

Im looking for a proper way of doing this.

example:

lets say the value in the database is NULL, I want it to show "-" when displaying, but I dont want to save "-" in the database. (I also don't want to use "get...Value" mutators for every value)

Upvotes: 0

Views: 462

Answers (1)

Douwe de Haan
Douwe de Haan

Reputation: 6646

Solution 1

Since PHP 7 there is a new feature called the Null Coalescing operator. It returns the first operator when it exists and is not NULL:

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

Which is the same as this:

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

Solution 2

Another solution would be a little bit harder, but doable:

Create a base model to which you extend all the other models:

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];
        }
    }
}

Now extend all the models you want to this new class and create an array of 'attributes to replace':

class User extends BaseModel {

    protected $emptyAttributes = ['name', 'email'];

}

This should automatically replace the attributes name and email when they are empty, NULL or a string of only spaces.

Side note: You could also move the functionality to a trait (which could be a more elegant solution, but that's up to you).

Upvotes: 3

Related Questions