Laravel Add An Unique Index To A Table

  • Execute the following command to create a migration file under the database directory in a Lavarel project:
    php artisan make:migration add_unique_index_to_tablename --table=tablename
  • In the created file, add the command to create a unique index under the function up
    public function up()
        {
    
            Schema::table('test', function (Blueprint $table) {
    
                $table->unique('name'); //this will generate a key name 'test_name_unique'
                $table->unique(['field1','field2']); //compound key
                
            });
        }

    and drop the index under the function

    public function down()
        {
            Schema::table('test', function (Blueprint $table) {
                $table->dropUnique('test_name_unique');
            });
        }
  • Run the migrations using
    php artisan migrate

    and that’s all.