Netra
Netra

Reputation: 338

Laravel 5 Mysql duplicate entry error

I'm using Laravel 5 to insert some entries in to the database but I get the following error:

SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '1' for key 'category_id' (SQL: insert into products (product_name, product_price, category_id) values (asdaszzz, 123, 1))

As I understand the problem is that the value that I want to add in the category_id table allready exist in other entry, but the thing is that the category_id table is not an UNIQUE key. Below I posted the migration:

public function up()
{
    Schema::create('products', function($table)
    {
        $table->increments('id');
        $table->integer('category_id')->unsigned();
        $table->string('product_name', 255)->unique();
        $table->decimal('product_price', 10, 4);
        $table->dateTime('updated_at')->default(DB::raw('CURRENT_TIMESTAMP'));
    });

    Schema::table('products', function($table) {
        $table->foreign('category_id')->references('id')->on('categories');
    });
}

Upvotes: 0

Views: 1602

Answers (2)

maztch
maztch

Reputation: 1697

Add nullable to category_id

$table->integer('category_id')->unsigned()->nullable();

Upvotes: 2

maztch
maztch

Reputation: 1697

Try adding table key...

public function up()
{
    Schema::create('products', function($table)
    {
        $table->increments('id');
        $table->integer('category_id')->unsigned();
        $table->string('product_name', 255)->unique();
        $table->decimal('product_price', 10, 4);
        $table->dateTime('updated_at')->default(DB::raw('CURRENT_TIMESTAMP'));

        $table->index('category_id');

        $table->foreign('category_id')->references('id')->on('categories');
    });
}

Upvotes: -1

Related Questions