How can i add new colum in existing table as a foreign in laravel 9

46 Views Asked by At

I was trying to add a new column as a foriegn key in existing table in laravel 9. But, it continuously giving SQL error. I want to create a simple category_id as a foreign_key in brand table.

The below code doesn't work,

$table->integer('category_id')->unsigned()->nullable()->after('password');
            $table->foreign('category_id')->references('id')->on('categories')->onDelete('SET NULL');
2

There are 2 best solutions below

0
bagher keshmiri On

Your category_id must be of big integer type or create user column like this

$table->unsignedBigInteger('device_id')->index()->nullable();

and if your table exist create new migration class and alter table to add new column in your table

0
francisco On

try:

$table->foreignId('category_id')->after('password');
$table->foreign('category_id')->references('id')->on('categories')->onDelete('SET NULL');

See more about DB Column Types.