Search code examples
laravelcircular-dependencylaravel-migrations

Laravel Schema Builder error creating circular reference


I have a Users table and a Companies table

Users table has a column 'company_id' which references Companies.id and Companies has a column 'assignation' which references Users.id

Obviously, no matter what table I attempt to create first, I get an error saying that it cannot create the reference Constraint because the other table does not exists.

I can do this manually, but I was looking for a way to use a standard Laravel migration.

Is there a workaround for this?

here is my code:

Schema::create('companies', function($table) {

            $table->increments('id');
            $table->string('name');
            $table->integer('priority');
            $table->string('color');
            $table->string('shortname');

            $table->integer('assignation');

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

            $table->timestamps();

        });

Schema::create('users', function($table) {

            $table->increments('id');
            $table->string('username');
            $table->string('password');
            $table->string('email');
            $table->integer('security');
            $table->string('token');

            $table->integer('company_id');

            $table->foreign('company_id')->references('id')->on('companies');

            $table->timestamps();

        });

Solution

  • You can simply add the foreign key constraint after both tables have already been created:

    Schema::create('companies', function($table) {
    
            $table->increments('id');
            $table->string('name');
            $table->integer('priority');
            $table->string('color');
            $table->string('shortname');
    
            $table->integer('assignation');
    
            $table->timestamps();
    
        });
    
    Schema::create('users', function($table) {
    
            $table->increments('id');
            $table->string('username');
            $table->string('password');
            $table->string('email');
            $table->integer('security');
            $table->string('token');
    
            $table->integer('company_id');
    
            $table->foreign('company_id')->references('id')->on('companies');
    
            $table->timestamps();
    
        });
    
    Schema::table('companies', function($table)
        {
            $table->foreign('assignation')->references('id')->on('users');
        });
    

    You can do this in a separate migration, or as a separate code block in the users table migration.