maxxd Posted August 28, 2021 Share Posted August 28, 2021 (edited) 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 August 28, 2021 by maxxd forgot to add the migration Quote Link to comment https://forums.phpfreaks.com/topic/313616-laravel-eloquent-nullable-unique-constraint/ Share on other sites More sharing options...
maxxd Posted August 28, 2021 Author Share Posted August 28, 2021 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. 1 Quote Link to comment https://forums.phpfreaks.com/topic/313616-laravel-eloquent-nullable-unique-constraint/#findComment-1589426 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.