Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

goeroe's avatar

Schema > nullable + unique

In one of my tables I use a company field that should be unique but also can be NULL. I added it to my schema as...

$table->string('company', 150)->unique()->nullable();

but I get an error: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '' for key ...

MySQL reference says: A UNIQUE index creates a constraint such that all values in the index must be distinct. An error occurs if you try to add a new row with a key value that matches an existing row. For all engines, a UNIQUE index allows multiple NULL values for columns that can contain NULL.

What am I missing here?

0 likes
5 replies
constb's avatar

@goeroe check how you're saving them. it seems you set company to an empty string somewhere. empty string is not a null.

2 likes
rodrigo.pedra's avatar
Level 56

@constb is correct, you're writing empty strings which are not NULL

You could write a mutator [ http://laravel.com/docs/5.0/eloquent#accessors-and-mutators ] in your Model to automatically set the company attribute to NULL when it is an empty string:

public function setCompanyAttribute($value) {
    if ( empty($value) ) { // will check for empty string, null values, see php.net about it
    $this->attributes['company'] = NULL;
    } else {
        $this->attributes['company'] = $value;
    }
}
9 likes
goeroe's avatar

I use TheModelname::create($request->all()); to store them so isn't this done automatically in this case?

rodrigo.pedra's avatar

An empty string "" is different from NULL both for PHP and MySQL. Laravel will never convert one to another automatically because for both languages they are different values.

If you add the mutator, Laravel will convert it to NULL properly, even on TheModelName::create(...), because internally it uses the ->fill(...) method whicj will check if the attribute has a mutator before setting it.

But every time you want empty strings to be converted to NULL before writing to the Database you'll have to add a mutator for each attribute

2 likes

Please or to participate in this conversation.