Setting null values only on certain fields

Submitted by meigwilym - 10 years ago

Often a foreign key needs to be set to NULL. On my projects I often use a drop down for this, and using an empty string as an option value does not work. I (hopefully) improved on this method[1] to set null values only on certain fields when saving a model. The original idea is from stackoverflow[2]. This method uses a BaseModel from which all models inherit. Any FK fields should be added to the model's $nullable property (an array). The work is done by the BaseModel. [1] http://laravelsnippets.com/snippets/set-fields-to-null-instead-of-empty-value-to-avoid-problems-with-nullable-foreign-keys [2] http://stackoverflow.com/questions/17452923/empty-string-instead-of-null-values-eloquent/19101473#19101473

// BaseModel Class

  protected $nullable = [];

  /**
   * Listen for save event
   */
  protected static function boot()
  {
    parent::boot();

    static::saving(function($model)
    {
      self::setNullables($model);
    });
  }

  /**
   * Set empty nullable fields to null
   * @param object $model
   */
  protected static function setNullables($model)
  {
    foreach($model->nullable as $field)
    {
      if(empty($model->{$field}))
      {
        $model->{$field} = null;
      }
    }
  }
  

// In my model class, e.g. Comment

  protected $nullable = ['post_id'];