Milind Daraniya

How to Create a Laravel Float Data Type Migration

Published September 23rd, 2023 20 min read

Laravel provides a convenient way to define and modify database tables using migrations. If you need to store decimal or floating-point values in your database, you can use the float data type. In this tutorial, we'll guide you through the process of creating a Laravel migration with a float data type.

Step 1: Create a Migration

To create a new migration, you can use the make:migration Artisan command. For example, to create a migration for a products table with a price column of the float data type, run the following command:

php artisan make:migration create_products_table

This will generate a new migration file in the database/migrations directory.

Step 2: Define the Column

Open the generated migration file and define the price column with the float data type. You can also specify the number of total digits and decimal places for the float column.

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateProductsTable extends Migration
{
    public function up()
    {
        Schema::create('products', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->float('price', 8, 2); // 8 total digits, 2 decimal places
            // Add other columns as needed
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::dropIfExists('products');
    }
}

In the example above, the price column is defined with a total of 8 digits and 2 decimal places.

Step 3: Run the Migration

After defining the column, save the migration file and run the migration to create the products table:

php artisan migrate

This will execute the up method of the migration, creating the table with the specified columns.

Step 4: Verify the Migration

To verify that the migration was successful, you can use a database management tool, the Laravel Schema Builder, or a command-line tool like tinker to inspect the structure of the products table.

php artisan tinker

// Use the schema builder to show the table structure
>>> Schema::getColumnListing('products');

Conclusion

Using the float data type in Laravel migrations allows you to store decimal or floating-point values in your database tables. By defining the column with the desired precision and decimal places, you can accurately represent numerical values in your application. Migrations provide a structured and organized way to manage your database schema changes and ensure consistency across your application's data storage.