nullEmptyCollumns = [ * "name" * ]; * } */ trait NullEmptyStringAttributeTrait { /** * Enables settings specified collumns * @var array|null */ protected $nullEmptyCollumns = null; /** * Set a given attribute on the model. * * @param string $key * @param mixed $value * @return void */ public function setAttribute($key, $value) { // should we null the attribute if ($this->canNullAttributeValue($key, $value)) { $value = null; } // call the parent attribute seting parent::setAttribute($key, $value); } /** * Checks the given attribute with value, detects if the value should * be nulled on empty string * * @param string $key * @param mixed $value * @return bool */ public function canNullAttributeValue($key, $value) { // filter collumns (optional setting) if (is_array($this->nullEmptyCollumns) && !in_array($key, $this->nullEmptyCollumns)) { return false; } // check if the value is string and the trimed value is empty // first check without trim for non needed trim call return is_string($value) && ($value === "" || trim($value) === ""); } }