Preston Garvey
Preston Garvey

Reputation: 1421

How to make combination of two columns as a unique key?

I have this table :

public function up()
{
    Schema::create('edition', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('volume');
        $table->text('cover')->nullable();
        $table->enum('number', ['1', '2']);
        $table->timestamps();
    });
    Schema::table('journal', function(Blueprint $table) {
        $table->foreign('id_edition')->references('id')->on('edition')->onDelete('cascade')->onUpdate('cascade');
    });
}

I wanted to make the combination of column Volume and Number as a unique key. For example, there is a data "Volume 1, Number 1" and when user insert the same combination it will throw an error message that the data already exist. Is there a way I can do this in Laravel ?

Upvotes: 5

Views: 8211

Answers (2)

geoandri
geoandri

Reputation: 2428

You can also use uniquewith-validator package that allows you to validate a unique combination of fields like this

'field1' => 'required|unique_with:table_name,field2'

The above code will check if the combination of field1 and field2 is unique in the table with the given table_name.

Upvotes: 1

Huzaib Shafi
Huzaib Shafi

Reputation: 1138

Just include the following snippet inside the up() method

$table->unique(['volume','number']);

By having this constraint set, if you insert 'Volume 1 , Number 1` once it'll be fine. However, if you try to do the same again, it'll throw an error.

Conditions:

  1. You are using some good DBMS, such as MySQL and not SQLITE
  2. You successfully migrated this change into the database.

Upvotes: 15

Related Questions