Foreign Key Constraint Fails On Existing Key

- 1 answer

In an existing Laravel project we encounter a vague problem when inserting a new record in our mysql database. The workflow is like this, whenever we create a new company, we also create users which belong to that company, somehow when submitting the new user, the foreign key constraint fails while we are 100% certain that key exists, and that we have the right key in hands.

Even stranger is that sometimes the creation goes well,and we can insert many users after that without any problems.

I hope that someone can point me in the right direction on how to proceed or debug this further.

EDIT: I've added some code, i don't think there is anything special here, except for the nullable on the foreignkey. This is a relative new addition, because not every user belongs to a company, so that's why I added that one.

I think the question would be: how can a foreign key fail, when you know (verify) that this key exists, is the right key and is 100% sure of the right type.

    $company = new Company();
    $company->showLicence = (int)$request->get('showLicence');


    //create a zero-user for each company to be able to login support    staff
    $user = new User();

    $user->name = "user";

    $user->password = bcrypt('password');
    $user->company_id = $company->id;

//user migration
Schema::create('users', function (Blueprint $table) {
        $table->string('password', 60);



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


In your migration code, the foreign key company_id on users actually refers to itself, not the company table. Change ->on('users') into ->on('companies').

As an additional tip, if your Company Eloquent model has a users relation (a method returning $this->hasMany('User');), you can insert the new user as follows:

$user = $company->users()->create([
    'name' => 'user',
    'password' => bcrypt('password'),