Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

AbdulBazith's avatar

How to add a foreign key to a table after migration done laravel

Guys i have doubt.

i have a table with 4 columns.

think that, i have a table product with 4 columns product_name, rate, min quantity, date

i have migrated the table so the table is created in phpmyadmin.

but i forget to add product_category_id column in the product table with foreign key.

now how can i add a column product_category_id with foreign key constrain in product table

Kindly some one suggest pelase

0 likes
20 replies
Nakov's avatar

What I do in this case is if the migration is not already pushed to a production site and it is only locally, you can:

  1. Edit your current migration and add the extra field with the foreign key constraint.
  2. Delete the product table from the database.
  3. Delete the row that contains the migration file name from the migrations table manually.
  4. Run php artisan migrate again.

If it is already used by other people in the team or on production, you can create a new migration adding the extra field.

Snapey's avatar

create a new migration and add the extra column

php artusan make:migration --table=product

the table= part tells laravel to adjust the existing table , not create a new one

SafeMood's avatar

@abdulbazith

u can use

php artisan make:migration add_product_category_id_to_product --table=product

if ur other table name is categories

Foreign Key : product_category_id

$table->foreign('product_category_id')->references('id')->on('categories');

Or can just use php artisan migrate:rollback

add ur column to the same migration file then migrate again

but this will erase any data in ur table

u can alaways take a look to the Documentation

https://laravel.com/docs/5.8/migrations#foreign-key-constraints

AbdulBazith's avatar

@nakov @safemood thank you soo much for you responses.

but if i follow you methods, my data will be erased.

i need the data in it.

and being open, i need to add the column for all the tables.

just for example i have given product_category_id.

but truely, i need to add hotel_id column with foreign key in all my 26 tables.

link: https://laracasts.com/discuss/channels/laravel/guys-need-a-big-suggestion-for-login-permission-for-different-users-laravel

for the above reason only i asked

if i change it locally then how can i do the same change in server without data erased??

1 like
AbdulBazith's avatar

@snapey thank you so much for you response.

i used ur code

php artisan make:migration --table=products

it showed error

Not enough arguments (missing: "name").

actually i need to add the hotel_id for all my tables. product_category is just for example i mentioned.

to add a extra column with foreign key constrain in al tables in local and in server without deleting data? how it is possible???

Snapey's avatar

sorry I was so focussed on telling you to add the table= command I forgot the name of the migration

but have you forgotten how migrations work?

should be. php artisan make:migration add-hotel-to-tables --table=products

or any name you like.

Now, in this migration class you can do whatever you want with your tables, and as many tables as you like

If you have 26 tables though, with data you cannot lose, I have not a clue how you will populate these tables with the hotel_id value?

To add the column

Schema::table('product', function (Blueprint $table) {
    $table->unsignedInteger('hotel_id')->nullable();
});

you can repeat this in the same file for all your other tables

The column is nullable since you already have data in the table and initially this column will be empty

1 like
SafeMood's avatar

@ABDULBAZITH - @abdulbazith

ur welcome

26 tables i guess u should first export ur dataabse as a backup

then u can use iSeed to save ur data in seeders its a laravel package that provides a method to generate a new seed file based on data from the existing database table.

after that make empty ur database dont drop it just select all tables and choose empty

go to ur migration folder and delete all ur migrations

use can now genrate all those migration by "Laravel Migrations Generator"

it Generate Laravel Migrations from an existing database

migrations-generator

php artisan help migrate:generat just use this code

Inverse seed generator (iSeed)

php artisan iseed my_table,another_table put all ur table names that way

now u can drop ur database tables and use

php artisan migrate --seed

it will make ur tables and fill them with data as they was

Advice: don't play with database in production

YeZawHein's avatar

@abdulbazith If u don't want to delete data, go to phpmyadmin

1.Go to your database
2.Click your table column
3.Click structure on menu bar
4.Click Relation view 

U can add foreign key whatever u want.

Btw, don't forget to edit your current migration table and add foreign field in your project.

AbdulBazith's avatar

@yezawhein thank you so much for your response.

i tried ur method by following through net, but i face problem. violation error, add or update foreign key

like this it showed error.

AbdulBazith's avatar

@safemood

the idea is tooo big. i just made sql commands i did it.


ALTER TABLE `users`
    ADD COLUMN `hotel_id` INT(10) unsigned AFTER `user_name`;


ALTER TABLE `users`
  ADD KEY `users_hotel_id_foreign` (`hotel_id`);



ALTER TABLE `users`
  ADD CONSTRAINT `users_hotel_id_foreign` FOREIGN KEY (`hotel_id`) REFERENCES `hotel_registrations` (`id`);


it succesfully done.. but really thank you soo much for ur suggestion and help.

really it helped me lot

1 like
AbdulBazith's avatar

@snapey sorry i forgot the migration syntax in tension.

i tried

php artisan make:migration add-hotel-to-tables --table=products

and changed to

 $table->integer('hotel_id')->unsigned()->after('id')->nullable();
            $table->foreign('hotel_id')->references('id')->on('hotel_registrations');

php artisan migrate worked correctly

but in the same migration file if i just change the table name and do php artisan migrate then it says nothing to migrate.

so i followed sql commands


//this is for users table

ALTER TABLE `users`
    ADD COLUMN `hotel_id` INT(10) unsigned AFTER `user_name`;


ALTER TABLE `users`
  ADD KEY `users_hotel_id_foreign` (`hotel_id`);



ALTER TABLE `users`
  ADD CONSTRAINT `users_hotel_id_foreign` FOREIGN KEY (`hotel_id`) REFERENCES `hotel_registrations` (`id`);



just i made duplication of this code and changed the table name and foreign key name thats it.

for all tables the column with primary key is added.

but really u gave much more explanation thank you thank youuu soooo much..

and for If you have 26 tables though, with data you cannot lose, I have not a clue how you will populate these tables with the hotel_id value?

for this answer is

i will do

where ('hotel_id',Auth::user()->hotel_id)

so based on this the records are fetched.

Kindly refer this link: https://laracasts.com/discuss/channels/laravel/guys-need-a-big-suggestion-for-login-permission-for-different-users-laravel

for my changes plz

SafeMood's avatar

@ABDULBAZITH - ur welcome any time

but using sql cmd u will lose your settings by losing the data or changing the environment

mkbat's avatar

@SAFEMOOD - To create a foreign key relationship you need to be sure that the column on the reference is using "unsignedInteger" as type. Another thing that you need to know is that if you already ran a migration the only way to reverse it is running "rollback" command or editing the migration table on your DB. Migrations need be planned and heavenly tested on development environment.

php artisan make:migration add_foreign_key --table=products

Add Column

Schema::table('products', function (Blueprint $table) {

    // To Create column
    $table->unsignedInteger('product_category_id')->nullable()->references('id')->on('categories');
});

Updating Column

Schema::table('products', function (Blueprint $table) {
   
    // Change to UnsignedInteger
    $table->unsignedInteger('product_category_id')->change();
    
    // Updating relationships
    $table->foreign('product_category_id')->references('id')->on('categories')->change();
});

This changes will not remove any data from your DB. But anyways TEST IT before do anything on your production DB. Let me know if you have any questions.

SafeMood's avatar

@MKBAT - thnx good pointing

but runnig rollback will erase data coz it will drop last migrations

i hope it work for him

1 like
Snapey's avatar
Snapey
Best Answer
Level 122

Learn how to use migrations !

you can repeat this in the same file for all your other tables

In the same file - not by changing the code you already ran;

Schema::table('product', function (Blueprint $table) {
    $table->unsignedInteger('hotel_id')->nullable();
});

Schema::table('purchase', function (Blueprint $table) {
    $table->unsignedInteger('hotel_id')->nullable();
});

Schema::table('bookings', function (Blueprint $table) {
    $table->unsignedInteger('hotel_id')->nullable();
});

Schema::table('staff', function (Blueprint $table) {
    $table->unsignedInteger('hotel_id')->nullable();
});

... whatever, whatever


Start hacking away with phpmysql and you will soon forget all the changes you made and will be unable to reliably perform the same on production.

You also then have database state that is not in your code repo and cannot be rebuilt by someone else.

3 likes
AbdulBazith's avatar

@mkbat thank you so much for your response.

as i said i tried the sql commands it was some what easy.

but thank you so much for your response

1 like
AbdulBazith's avatar

@snapey thank you so much for your response.

ya i understood that changing in the single file and if i migrate it it works.

Start hacking away with phpmysql and you will soon forget all the changes you made and will be unable to reliably perform the same on production.

this you are saying that changing in sql cannot be remembered for future so there i will face problems thats what u are trying to say??

You also then have database state that is not in your code repo and cannot be rebuilt by someone else. whats this meaning???

Snapey's avatar

I mean that if you dont use migrations for everything then starting with a clean database then ruuning the migrations you do have will not end up with a working copy of your application

AbdulBazith's avatar

@snapey yaa u are right snapey.

i agree with you.

as you said i need to learn about migrations.

thank you for you suggestions..

ajmalsarim's avatar

How to do via Controller

1- Set a Rought: Route::get('foreignkeyforimg', "foreignkey@index"); 2- Create controller With Foreignkey Name. 3- Foreignkey Controller with extend from Migration class.

namespace App\Http\Controllers;

use Illuminate\Http\Request; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Validator; use Illuminate\Support\Facades\Schema; use App\Image; use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint;

class Foreignkey extends Migration { function index(){

    Schema::table('images', function (Blueprint $table) {
       

        $table->foreign('sub_cat_id')
            ->references('id')
            ->on('subcategories')
            ->onDelete('cascade');
    });
}

} 4- Go to data base and delete old primary key manualy from the table

Please or to participate in this conversation.