Search code examples
mysqllaravel-5laravel-migrationsartisan-migrate

How to get all models/migrations names in laravel and add single new column


I have 88 tables in the database and I need one new column in each the table one single solution is I make a migration and write 88 functions for all tables to add the new column as well as 88 to remove that column.

enter image description here

Is there any way to get all the table names in 1 variable and then by using foreach add a new column by a single piece of code?

  1. get all table name in variable

  2. by foreach loop add new column to that particular variable

$allTables=?
foreach($allTables as $singleTable){
    add new column
}

But HOW? I want to add team_id in all the tables but I need an optimal solution.

I am using laravel 5.4 version.


Solution

  • Try the following.

    // Get the default database name
    $dbName = config('database.connections.' . config('database.default') . '.database');
    
    $tables = DB::select('SHOW TABLES');
    
    foreach($tables as $table)
    {
        Schema::table($table->{'Tables_in_' . $dbName}, function($table) {
            // Add the column
            $table->string('some_column');
        });
    }
    

    To understand what's going on analyze the $tables variable, but should be quite straightforward.