This forum has moved to a new location and is in read-only mode. Please visit talk.octobercms.com to access the new location.

nanohard
nanohard

Trying to store money in a database as cents (integer).

If I add code to beforeSave() and use an integer, the code works. 80 becomes 8000 cents.

But if I use a decimal when the field is either type:text or type:number it gets rounded first. Not sure why this is. I also tried beforeValidate() and that didn't work at all. 8.10 becomes 8 instead of 810.

Here's the code I'm using:


public function beforeSave()
    {
        $length = strlen($this->pay_rate);

        if ( !strstr('.', $this->pay_rate) ) // without a decimal; this 'if' block works as intended; does not work with beforeValidate()
        {
            switch($length)
            {
                // if one or two digits, assume "dollars"
                case 1:
                case 2:
                    $this->pay_rate = $this->pay_rate . '00';
                    break;
                // if three or four digits, assume "cents"
                case 3:
                case 4:
                    break;
                // all else, set pay_rate to '0'
                default:
                    $this->pay_rate = '0';
                    break;
            }
        }

        // This block does not work, like it rounds it before it even gets to this point. Also tried beforeValidate() and it doesn't work.
        elseif ( strstr('.', $this->pay_rate))// && (strrpos($this->pay_rate , '.', -3)) ) // with two digits following a decimal
        {
            switch($length)
            {
                // if one or two digits, assume error (how to raise error message?)
                case 1:
                case 2:
                    $this->pay_rate = '0';
                    break;
                default:
                    $this->pay_rate = str_replace('.', '', $this->pay_rate);
                    break;
            }
        }

        else { $this->pay_rate = '0'; } // assume error, set pay_rate to '0'
    }

Last updated

nanohard
nanohard

Solved by moving the code (still in the model) to:


public function setPayRateAttribute($value)
    {
        $this->attributes['pay_rate'] = $value * 100;
    }

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

1-2 of 2

You cannot edit posts or make replies: the forum has moved to talk.octobercms.com.