DEV Community

JohnDivam
JohnDivam

Posted on • Updated on

Laravel money model

In Laravel, "Laravel Money" is not a built-in package or feature. However, you might be referring to handling money-related data in your Laravel application. To handle money values effectively, you can use the Laravel's native Eloquent attributes and mutators. Here's how you can achieve this:

namespace App\Models;


class Money
{
    private $cent;

    private function __construct($cent)
    {
        $this->cent = $cent;
    }

    public static function fromCent($cent)
    {
        return new static($cent);
    }

    public function inCurrencyAmount()
    {
        return round($this->cent / 100, 2);
    }

}

Enter fullscreen mode Exit fullscreen mode

Using with Service model , deservedAmount column

$deservedAmount = (Money::fromCent(Service::sum('deservedAmount') ?? 0))->inCurrencyAmount();

Enter fullscreen mode Exit fullscreen mode

Add seter/geter in Service model

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

    public function getDeservedAmountAttribute($value)
    {
        return $value / 100;
    }
Enter fullscreen mode Exit fullscreen mode

Top comments (0)