Alexandre Thebaldi Alexandre Thebaldi - 3 months ago 32
PHP Question

Laravel: How check if model field is nullable on database

I'm set all empty fields to

null
when saving

Using OctoberCMS model event
beforeSave
(equivalent to Laravel model saving)

public function beforeSave()
{
// $this => the model
foreach ( $this->toArray() as $name => $value )
{
if ( empty( $value ) ) {
$this->{$name} = null;
}
}
}


The problem is when field has a default value defined on database (mysql), for example:

$table->integer('value')->default(1);


I need to get an array of all nullable or not nullable fields of current model.

How do this?

Answer

Laravel/Eloquent have no clue about the structure of your database. Assumption is made that whatever operations you implement, database structure is ready for them.

You could query the database to get information about columns. For MySQL you'd need to run

show columns from <table_name>;

This will result in additional queries sent to the database.

A better option, in my opinion, is to just store such information in model classes, e.g. in

protected $notNullable = ['field1', 'field2'];

in a similar fashion like $fillable or $guarded fields are stored. When you write your models you should be aware which columns are nullable and which aren't, so it should be the easiest solution.