5
votes

I have a Address table in my mySQL database with some fields.

On my form i ask a user to input values for these fields. But the street field is not required . So when my form gets submitted my Column Street is just empty in my database. This works fine and gives no errors without setting the column to accept NULL .

So my question is :

What is the benefit of setting the Street column to nullable?

Example migration (Laravel) without nullable:

$table->string('street');

Example Migration with nullable

$table->string('street')->nullable();

Both work fine .

1
In your case, it probably doesn't really matter. In some other application, an empty string may not be the same thing as the absence of a string, so null serves a purpose there. I generally make fields that could be left out nullable as a best practice, but it's not something you have to do.Joel Hinz
can you give an example where it will matter?Christophvh
Unless you know you need the difference, it is unlikely to matter. :)Joel Hinz
Ok, so basically the answer is to always use nullable because it will always work as intended? You can post that as an answer so i will accept it :)Christophvh
In this case I don't think it matters but nullable can be useful for foreign key columns. Let's say you have a user_id foreign key on your address table and for some reason you have an address you need to store which doesn't belong to a user, you'd be able to set that user_id column to null and it should still work without violating the foreign key constraints where an empty space would.user1669496

1 Answers

4
votes

It is just a good practice to use explicit instead of implicit where it's possible. So I'd go with nullable and is_null() checking for null.

With this approach you get less bugs, more readable code etc.