简体   繁体   中英

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?

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, eg 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.

Add this to your model or trait

use DB;
...
    protected static $_columns_info = NULL;
    protected static $_nullable_fields = NULL;
    public function is_nullable(string $field_name){
        if (is_null(static::$_columns_info) ){
            static::$_columns_info = DB::select('show columns from '.$this->gettable() );
        }
        if (is_null(static::$_nullable_fields) ){
            static::$_nullable_fields = array_map( function ($fld){return $fld->Field;}, array_filter(static::$_columns_info,function($v){return $v->Null=='YES';}));
        }
        return in_array( $field_name, static::$_nullable_fields );
    }

and use like

app(Model::class)->is_nullable(you_column_name)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM