Support Laravel Version: Laravel 8, Laravel 9, Laravel 10, Laravel 11 With Latest All Version Support.
In Laravel you can add columns to an existing table using migrations. Here’s a step-by-step guide on how to do this:
1. Create a Migration: You can create a new migration using the Artisan command-line tool. Open your terminal or command prompt and run:
php artisan make:migration add_columns_to_table_name --table=table_name
Replace `add_columns_to_table_name` with a descriptive name for your migration, and replace `table_name` with the name of the table to which you want to add columns.
2. Edit the Migration File: Open the newly created migration file located in the `database/migrations` directory. Inside the `up` method, use the `Schema::table()` method to modify the existing table and add new columns. For example:
use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class AddColumnsToTableName extends Migration { public function up() { Schema::table('table_name', function (Blueprint $table) { // Add new columns $table->string('new_column1'); $table->integer('new_column2')->default(0); // You can add more columns as needed }); } public function down() { Schema::table('table_name', function (Blueprint $table) { // If you need to rollback, define how to drop the columns $table->dropColumn('new_column1'); $table->dropColumn('new_column2'); // Define drops for other columns as needed }); } }
3. Run the Migration: After defining your migration, save the file and then run the migration using Artisan:
php artisan migrate
This command will execute any outstanding migrations and apply the changes to your database schema.
That’s it! Now you’ve successfully added new columns to an existing table using a migration in Laravel.