eComEvo eComEvo - 4 months ago 7
PHP Question

Mutators ignored when model saved

I have a model that stores decimals as integers that are supposed to be converted when read/written from the database using mutators:

public function getPrice($value)
{
return $value / 100;
}

public function setPrice($value)
{
$this->attributes['price'] = round($value, 2) * 100;
}


However, the mutators are never called.

For instance, if I do
create/insert/save
etc:

PriceHistory::create(['price' => 1234.25]);


I get this error:

Illuminate\Database\QueryException with message 'SQLSTATE[22P02]:
Invalid text representation: 7 ERROR:
invalid input syntax for integer:
"1234.25" (SQL: insert into "price_history" ("price") values (1234.25))'


What am I doing wrong here?

Answer

From docs:

Defining An Accessor

To define an accessor, create a getFooAttribute method on your model where Foo is the "camel" cased name of the column you wish to access.

So, it would be like this:

public function getPriceAttribute($value)
{
    return $value / 100;
}

public function setPriceAttribute($value)
{
    $this->attributes['price'] = round($value, 2) * 100;
}