Gilson PJ
Gilson PJ

Reputation: 3600

Adding a column with foreign key

My existing table is like below

Story
-------------------------------
| id | name | author_id | date |

Now I want to add one more foreign key column created_by how to add this without deleting the existing data. The existing data foreign key must be the admin id.

From this question I understood how to add a column without deleting all the existing data.

How to add column in a table using laravel 5 migration without losing its data?

I want to do this modification in my PC, test machine, live server. So I have to add the foreign key and also I have to find out the admin id from users table and assign to it. How to do this?

Upvotes: 1

Views: 222

Answers (2)

Vikash
Vikash

Reputation: 3561

Use @Eric Tucker answer for creating the migration

Now for updating the database with new values of created_by. I am writing you how i upgrade my code which it deals with different servers (In my case local, test & production).

Create route

Route::get('upgrade/createdBy','UpgradeController@upgradeCreatedBy')

Create UpgradeController

php artisan make:controller UpgradeController

In your UpgradeControlller.php

Class UpgradeController
{
  public function upgradeCreatedBy()
  {

   // write your logic for find the admin_id and assign your variable to $adminId

    $stories = Stories::all();
    $count = 0; 
    foreach($stories as $story)
    {
      $story->update(['created_by'=> $adminId]);
      $count ++;
    }

     return "$count rows updated successfully";
  }
}

Now run url http://your_domain/upgrade/createdBy in your browser on your different servers and your code will be upgraded.

Note :: delete your route and method,I would suggest to keep the controller file but delete the method you have written in controller. So that you can use this upgrade controller in future by just adding the route and method for different kind of upgrade.

This is how i do any db upgrade on multiple servers.

Upvotes: 0

Eric Tucker
Eric Tucker

Reputation: 6345

To add a column you can reference an existing table with the --table flag on the make:migration artisan command:

php artisan make:migration add_created_by_column_to_story_table --table=story

Then in your migration it will use the table() method instead of the create() method:

/**
 * Run the migrations.
 *
 * @return void
 */
public function up()
{
    Schema::table('story', function(Blueprint $table) {
        $table->integer('created_by');
    });
}

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    Schema::table('story', function(Blueprint $table) {
        $table->dropColumn('created_by');
    });
}

Upvotes: 1

Related Questions