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

I am trying to create a relationship between categories and products. I have provided the various columns for both tables and I am trying to link them using a foreign id (the category_id from the category table) but I keep getting this error.

Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint failsIntegrity constraint violation: 1452 Cannot add or update a child row but it does not answer the question

This is my Category table

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

public function up()
{
    Schema::create('categories', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->timestamps();
    });
}

And this is the product table

public function up()
{
    Schema::create('products', function (Blueprint $table) {
        $table->increments('id');
        $table->unsignedInteger('category_id');
        $table->string('name');
        $table->string('description');
        $table->string('image');
        $table->integer('price');
        $table->foreign('category_id')
            ->references('id')
            ->on('categories')
            ->onDelete('cascade');
        $table->timestamps();
    });
}

This is the category model.

class Category extends Model
{
 use HasFactory;

protected $fillable = [
    'name',
];


public function products()
{
    return $this->hasMany(Product::class);
}

}

This is the product model

class Product extends Model
{
    use HasFactory;

    protected $fillable = [
        'name',
        'description',
        'image',
        'price',
        'category_id',
    ];

    public function category()
    {
        return $this->belongsTo(Category::class);
    }

    public function setPriceAttribute($value)
    {
        $this->attributes['price'] = $value * 100;
    }
}

This is my Product Factory class

<?php
    
    namespace Database\Factories;
    
    use Illuminate\Database\Eloquent\Factories\Factory;
    
    class ProductFactory extends Factory
    {
       
        public function definition()
        {
            return [
                'name'=>$this->faker->unique()->word(),
                'description'=>$this->faker->text(),
                'image'=>$this->faker->imageUrl(100, 100),
                'price'=>$this->faker->numberBetween($min = 50, $max = 100),
                'category_id'=>$this->faker->randomDigit()
            ];
        }
    }

This is my db seeder class

class DatabaseSeeder extends Seeder

    {
       
        public function run()
        {
    
            Product::factory(20)->create();
        }
    }

This is the full error code I am getting please after running the db:seed

 INFO  Seeding database.  

Illuminate\Database\QueryException

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`econs`.`products`, CONSTRAINT `products_category_id_foreign` FOREIGN KEY (`category_id`) REFERENCES `categories` (`id`) ON DELETE CASCADE) (SQL: insert into `products` (`name`, `description`, `image`, `price`, `category_id`, `updated_at`, `created_at`) values (omnis, Facere autem excepturi velit dolorem voluptas. Dignissimos laboriosam quia numquam sint harum officia eum. A aspernatur ratione fuga ut nesciunt sit. Ex nisi maxime quas., https://via.placeholder.com/100x100.png/006611?text=aut, 5700, 4, 2022-10-10 11:49:55, 2022-10-10 11:49:55))

  at vendor/Laravel/framework/src/Illuminate/Database/Connection.php:759
    755▕         // If an exception occurs when attempting to run a query, we'll format the error
    756▕         // message to include the bindings with SQL, which will make this exception a
    757▕         // lot more helpful to the developer instead of just the database's errors.
    758▕         catch (Exception $e) {
  ➜ 759▕             throw new QueryException(
    760▕                 $query, $this->prepareBindings($bindings), $e
    761▕             );
    762▕         }
    763▕     }

      +16 vendor frames 
  17  database/seeders/DatabaseSeeder.php:26
      Illuminate\Database\Eloquent\Factories\Factory::create()

      +23 vendor frames 
  41  artisan:37
      Illuminate\Foundation\Console\Kernel::handle()

>Solution :

You’re using $this->faker->randomDigit() which creates a random digit, and doesn’t care if the category ID exists or not. For your factory, you can grab a random category and use it’s id:

'category_id'=>Category::inRandomOrder()->first()->id
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