Laravel - does not record price when value is NULL

0

I have a Laravel mutator to handle a field, but if the field is empty it does not save the default value in the database.

MODEL

/// PROMOÇÃO TROCA VIRGULA POR PONTO
public function setPromocaoAttribute($value)
{
    $value==null ? '0.00' : $this->attributes['promocao'] = str_replace(",", ".", $value);
}

Neither preset nor even bank works

In the database, you have to:

  

'promotion' decimal (8,2) NOT-NULL and also Default ('0.00')

I needed it to be saved as null, or as 0.00 but it is difficult kkk apparently only want to save if the value is greater than 0

    
asked by anonymous 26.07.2018 / 15:07

1 answer

2

You are returning the value '0.00' to nowhere, and when the entry is null, the field is not modified.

Instead of

public function setPromocaoAttribute($value)
{
    $value==null ? '0.00' : $this->attributes['promocao'] = str_replace(",", ".", $value);
}

Do

public function setPromocaoAttribute($value)
{
    $this->attributes['promocao'] = ($value == null) ? '0.00' :  str_replace(",", ".", $value);
}

Thus, the promocao attribute will receive '0.00' if $value is null.

Or, if you use PHP 7, you can use the ?? :

$this->attributes['promocao'] = str_replace(",", ".", $value ?? '0.00');
    
26.07.2018 / 15:22