John Davidson

php - Add same new columns to all existing migration tables at once

0 comments
Message:


Let's say I have 30 migration tables. Now I want to add 2 new columns to all existing migrations table.


$table->unsignedBigInteger('organogram_id')->nullable();
$table->unsignedBigInteger('project_id')->nullable();

//foreign
$table->foreign('organogram_id')->references('id')->on('organograms')->onUpdate('cascade')-
>onDelete('restrict');
$table->foreign('project_id')->references('id')->on('projects')->onUpdate('cascade')-
>onDelete('restrict');

In Laravel we can add new columns to a table.Is there any way to add same columns to multiple tables?
should I iterate through all migrations and the new columns or is there any other way?



My Answer:
One way to add the same new columns to multiple tables in Laravel is to create a new migration file that adds the columns to each table individually. Here's an example of how you can do this:

1. Create a new migration file using the artisan command:
bash
php artisan make:migration add_columns_to_tables


2. Open the newly created migration file and add the following code inside the `up` method:
php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Migrations\Migration;

class AddColumnsToTables extends Migration
{
public function up()
{
$tables = ['table1', 'table2', 'table3']; // Add all your table names here

foreach ($tables as $table) {
Schema::table($table, function (Blueprint $table) {
$table->unsignedBigInteger('organogram_id')->nullable();
$table->unsignedBigInteger('project_id')->nullable();

$table->foreign('organogram_id')->references('id')->on('organograms')->onUpdate('cascade')->onDelete('restrict');
$table->foreign('project_id')->references('id')->on('projects')->onUpdate('cascade')->onDelete('restrict');
});
}
}

public function down()
{
// Drop the columns if needed
}
}


3. Run the migration using the artisan command:
bash
php artisan migrate


This will add the new columns `organogram_id` and `project_id` to each table specified in the `$tables` array. Make sure to replace `table1`, `table2`, `table3`, etc. with the actual names of your migration tables.

By using this approach, you can add the same columns to multiple tables without having to manually edit each individual migration file.

Rate this post

4 of 5 based on 7582 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us