I want to create a column for price in a laravel schema.
public function up()
{
Schema::create('cameras', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('condition');
$table->string('price');
$table->string('type');
$table->timestamps();
});
}
Or is there an alternative data type I can use? As I don't see anything for monetary value in the documentation. Any help would be appreciated.
You can use decimal to precisely store price value:
$table->decimal('price', 9, 3);
Note that 9 is the precision, like 1234567.89 has a precision of 9,
And 3 is the number of decimal places, ie 123456.789 has a scale of 3In other words, if we use less decimal-places than 3, we can use remaining for real-number places.
See also: How do I interpret precision and scale of a number in a database?
Alternatively, you can also use big integer and store the amount in basic monetary unit like cents. Like this:
$table->bigInteger('price');
So if we want to store let's say $ 107.45 (107 dollars, 45 cents), we'd first multiply it by 100 and store 10745 in the price column. And upon retrieval divide by 100.
In other words, storing the lowest unit you think will be ever required, like storing Centi-meters instead of Meters (Centi is originally Greekish name for "0.01" number).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With