Laravel is a popular PHP framework that provides a simple and elegant way to build web applications. One of the key features of Laravel is its migration system, which allows you to define your database schema using PHP code and easily apply those changes to your database.
In this tutorial, we will look at how to define a price column in a migration in Laravel 10 beginners intermediate advanced 2 laravel. We will create a new migration that adds a price
column to a table, and we will define the column using Laravel’s schema builder.
Step 1: Create a new migration
First, we need to create a new migration file using the make:migration
Artisan command. Open up your terminal or command prompt and run the following command:
php artisan make:migration add_price_column_to_products_table --table=products
This command will create a new migration file in the database/migrations
directory of your Laravel application. The migration file will be named something like 2021_03_19_000000_add_price_column_to_products_table.php
, where the timestamp in the filename represents the current date and time.
Step 2: Define the price column in the migration
Open up the new migration file in your code editor of choice. In the up()
method, we need to define the new price
column that we want to add to the products
table. We can do this using Laravel’s schema builder.
Here’s an example of what the migration file might look like:
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class AddPriceColumnToProductsTable extends Migration
{
public function up()
{
Schema::table('products', function (Blueprint $table) {
$table->decimal('price', 8, 2)->after('description');
});
}
public function down()
{
Schema::table('products', function (Blueprint $table) {
$table->dropColumn('price');
});
}
}
In this example, we’re adding a new price
column to the products
table with a precision of 8 digits and a scale of 2 digits after the decimal point. We’re also specifying that the new column should be added after the description
column in the table.
Step 3: Run the migration
Once you’ve defined the new column in your migration file, it’s time to run the migration using the migrate
Artisan command. Open up your terminal or command prompt and run the following command:
php artisan migrate
This will apply the changes defined in your migration file to your database. In this case, it will add the new price
column to the products
table.
Conclusion
Defining a price column in a migration in Laravel 8 is a straightforward process using Laravel’s schema builder. By following the steps in this tutorial, you should now be able to define and apply changes to your database schema using Laravel’s migration system.