18

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.

Top-Master
  • 7,611
  • 5
  • 39
  • 71
AltBrian
  • 2,392
  • 9
  • 29
  • 58

2 Answers2

34

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 3

In 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).

Top-Master
  • 7,611
  • 5
  • 39
  • 71
Sumit Wadhwa
  • 2,825
  • 1
  • 20
  • 34
7

There is 'float' type for your purpose it seems fine unless you don't want to save currency too:

$table->float('amount')

Available types are listed in documentation. https://laravel.com/docs/5.4/migrations#creating-columns

If you do want to save currency with price you will have to use string , or create a new column for currency-type can be another work around.

MaxiGui
  • 6,190
  • 4
  • 16
  • 33
Fahad Azhar
  • 188
  • 1
  • 6