Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Integrity constraint violation laravel 9

I am using Laravel 9 to set up my migrations but I keep getting this error Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails I have looked this up and I’m very confused as my user_id in table urls does reference the id column on the users table?

I have also ensured that I have protected fillable for the user_id in my url.php model which I saw as an answer to a similar question.

public function up()
    {
        Schema::create('urls', function (Blueprint $table) {
            $table->id();
            $table->text('full_url');
            $table->string('short_url')->unique();
            $table->foreignId('user_id')->constrained();
            $table->timestamps();
        });
    }
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
    }

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Foreign key constraints are one of the mechanisms used to ensure data integrity. In this case, it means that the foreign key you’re about to insert must have a correspondence within the associated foreign table.

Let me give an example. Let’s say you have a posts table that has a user_id foreign key.
Then in your users table, you have the following ids: 1, 2, 3 and 4.
If you try to insert/update a post, the user_id provided must exist within the users table. So that means that if you tried to insert a new post that has a user_id of 7, it would fail because there’s no id of 7 in the users table.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading