Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a foreign key to nullable in Laravel

Tags:

php

mysql

laravel

I have a user_id set in log table and now have a problem that I sometimes need to store logs to actions performed by non-logged users.

When I run this migration

    Schema::table('users_log', function (Blueprint $table) {
        $table->unsignedInteger('user_id')->nullable()->change();
    });

I get an error

[Illuminate\Database\QueryException] SQLSTATE[HY000]: General error: 1832 Cannot change column 'user_id': used in a foreign key constraint 'users_log_user_id_foreign' (SQL: ALTER TABLE users_log CHANGE user_id user_id INT UNSIGNED DEFAULT NULL)

like image 492
naneri Avatar asked Dec 13 '22 18:12

naneri


1 Answers

You need to drop FK constraint first:

$table->dropForeign(['user_id']);

Then modify the column and add a new FK constraint.

Also, make sure you're doing this in a separate Schema::table() closures.

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

like image 111
Alexey Mezenin Avatar answered Dec 17 '22 22:12

Alexey Mezenin