Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why should i use/not-use a nullable field Laravel - MySQL

Tags:

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 .

like image 983
Christophvh Avatar asked Apr 07 '16 13:04

Christophvh


People also ask

What is the use of nullable in laravel?

It means the middle_name field can also store null values: as in inserting a value is not required. Imagine a registration form for example. Not everybody has a middle name. So in that case they would leave the middle_name field empty and in the database it'll be null .

How do you make an existing column nullable in laravel?

The code to change the column to nullable is as "nullable()->change()". ->nullable()->change(); For this example, we'll be using the route body and we will make the "posts" table "user_id" to be nullable.


1 Answers

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.

like image 81
Alexey Mezenin Avatar answered Sep 28 '22 03:09

Alexey Mezenin