Laravel - does not write price when value is NULL

Asked

Viewed 249 times

0

I have a Laravel mutator to treat a field, but if the field comes empty it does not save the default value in the bank.

MODEL

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

neither preset before nor even in the bank works

in the bank is OBS:(also already tried to leave NULL in the bank, even so does not update the field)

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

I needed it to be safe as null, or 0.00 but it’s hard kkk apparently only wants to save if the value is greater than 0

1 answer

2


You are returning the value '0.00' nowhere and when the entry is void, 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 attribute promocao will receive '0.00' if $value is void.

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

$this->attributes['promocao'] = str_replace(",", ".", $value ?? '0.00');
  • Ball show bro! worked perfectly, yes it is php 7. Thank you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.