Skip to content Skip to sidebar Skip to footer

Laravel Eloquent How To Create Unique Constraint With Duplicate Nulls

I'm usinq Laravel 5 with MS Sql Server 2014. I want to create a unique constraint but it should allow multiple null values. Here is code I'm using. Where 'passport_no' has to be un

Solution 1:

This is an ancient question, but sill needs answering. As stated above, SQL Server from 2008, including Azure SQL, supports a special index that will work around it. In your database migration you can check the driver used and substitute the database builder standard SQL with an MSSQL-specific statement.

This migration example is for Laravel 5+, and creates a users table with a unique, but nullable, api_token column:

publicfunctionup()
{
    Schema::create('users', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->timestamps();

        $table->string('name', 100)->nullable()->default(null);
        // etc.$table->string('api_token', 80)->nullable()->default(null);

        if (DB::getDriverName() !== 'sqlsrv') {
            $table->unique('api_token', 'users_api_token_unique');
        }
    });

    if (DB::getDriverName() === 'sqlsrv') {
        DB::statement('CREATE UNIQUE INDEX users_api_token_unique'
           . ' ON users (api_token)'
           . ' WHERE api_token IS NOT NULL');
    }
}

Solution 2:

you can use a unique Index and in its filter set your condition like

passport_no isnotnull

in this way you can solve your problem

Post a Comment for "Laravel Eloquent How To Create Unique Constraint With Duplicate Nulls"