Jump to content

Laravel eloquent nullable unique constraint


maxxd

Recommended Posts

Hi y'all. In my attendees table the attendee_code field must be unique if it is known - if not, we pretend it's fine and move on. I know that it's not the greatest idea in terms of data integrity, but given the business rules I have to work with, it is what it is. The only problem is that I'm getting a duplicate entry exception when a new record is entered into the DB with a null attendee_code if any other record has a null attendee_code. MySQL allows this, so I'm thinking this must be an eloquent thing - does anyone know what I'm missing?

    public function up()
    {
        Schema::create('attendees', function (Blueprint $table) {
            $table->id();
            $table->timestamps();
            $table->string('first_name');
            $table->string('last_name');
            $table->string('specialty');
            $table->string('attendee_code')->nullable();
            $table->string('npi_id')->nullable();
            $table->string('address_1')->nullable();
            $table->string('city')->nullable();
            $table->string('state')->nullable();
            $table->string('zip_code')->nullable();
            $table->unique('attendee_code');
        });
    }

 

Edited by maxxd
forgot to add the migration
Link to comment
Share on other sites

You know those times where explaining your issue gets you to think about it a different way and you immediately solve your problem? Yeah.

For anyone that happens across this with a similar issue, the problem was that the value being inserted was '', not null. So the duplicate entry was actually valid. I created a mutator in the model to return an actual null value if the attendee_code is empty, and everything works as expected now.

Thanks again to this forum for being my eternal rubber ducky.

  • Like 1
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.