1

In my Larave-8, I created a table using this migration:

public function up()
{
    Schema::create('profiles', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->bigInteger('user_id');
        $table->string('first_name',50);
        $table->string('last_name',50);
        $table->string('other_name',50)->nullable();
        $table->string('gender',20);
        $table->string('user_photo',350)->nullable();
        $table->integer('nationality_id');
        $table->string('marital_status',50);
        $table->date('dob')->nullable();
        $table->string('address', 300)->nullable();
        $table->integer('country_id')->nullable();
        $table->integer('state_id')->nullable();
        $table->integer('city_id')->nullable();
        $table->string('cv_file',350)->nullable();
        $table->text('summary')->nullable();
        $table->timestamps();

        $table->foreign('user_id')->references('id')->on('users');
    });
}

How do I alter the table through migration and add these:

        $table->foreign('nationality_id')->references('id')->on('countries');
        $table->foreign('country_id')->references('id')->on('countries');
        $table->foreign('state_id')->references('id')->on('state_origins');
        $table->foreign('city_id')->references('id')->on('cities');

Thanks

user11352561
  • 2,277
  • 12
  • 51
  • 102
  • Does this answer your question? [Laravel - add foreign key on existing table with data](https://stackoverflow.com/questions/44744733/laravel-add-foreign-key-on-existing-table-with-data) – Joseph May 05 '21 at 08:51

1 Answers1

0

create another migration like to alter existing table

public function up()
    {
        Schema::table('profiles', function (Blueprint $table) {
            $table->foreign('nationality_id')->references('id')->on('countries');
            $table->foreign('country_id')->references('id')->on('countries');
            $table->foreign('state_id')->references('id')->on('state_origins');
            $table->foreign('city_id')->references('id')->on('cities');
        });
    }

    public function down() {
        Schema::table('profiles', function (Blueprint $table) {
            $table->dropForeign('nationality_id');
            $table->dropForeign('country_id');
            $table->dropForeign('state_id');
            $table->dropForeign('city_id');
        });
    }
Chinh Nguyen
  • 1,246
  • 1
  • 7
  • 16