Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

schema builder laravel migrations unique on two columns

People also ask

How do I change a column to unique in Laravel migration?

$table->unique('slug'); So you add unique index to existing 'slug'.

What is foreign key in Laravel migration?

Foreign Keys Laravel also provides support for adding foreign key constraints to your tables: $table->integer('user_id')->unsigned(); $table->foreign('user_id')->references('id')->on('users'); In this example, we are stating that the user_id column references the id column on the users table.


The second param is to manually set the name of the unique index. Use an array as the first param to create a unique key across multiple columns.

$table->unique(array('mytext', 'user_id'));

or (a little neater)

$table->unique(['mytext', 'user_id']);

Simply you can use

$table->primary(['first', 'second']);

Reference: http://laravel.com/docs/master/migrations#creating-indexes

As an example:

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

        $table->integer('post_id')->unsigned();
        $table->integer('tag_id')->unsigned();

        $table->foreign('post_id')->references('id')->on('posts');
        $table->foreign('tag_id')->references('id')->on('tags');

        $table->primary(['post_id', 'tag_id']);
    });