Skip to content

Instantly share code, notes, and snippets.

@calebporzio
Created June 1, 2017 19:07
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save calebporzio/0a8353962fc943a5bf0cf40feeb27eea to your computer and use it in GitHub Desktop.
Save calebporzio/0a8353962fc943a5bf0cf40feeb27eea to your computer and use it in GitHub Desktop.
A handy accessor and mutator for storing amounts in cents and accessing and setting them in dollars
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class [Insert Name Here] extends Model
{
protected $guarded = [];
function getAmountInDollarsAttribute($dollars)
{
return sprintf('$%01.2f', $this->amount_in_cents / 100);
}
function setAmountInDollarsAttribute($dollars)
{
$dollars = str_replace('$', '', $dollars);
$this->amount_in_cents = (int) (((float) $dollars) * 100);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment