Created
December 1, 2015 05:16
-
-
Save benrowe/a9d6dd02e057d8795bb7 to your computer and use it in GitHub Desktop.
NullIfEmptyTrait for Laravel models
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* @author Ben Rowe <ben.rowe.83@gmail.com> | |
*/ | |
namespace App\Models; | |
/** | |
* Defines a list of model attributes that need to be handled as null fields | |
* When specific conditions are met (such as the value is empty) the | |
* value is automatically cast to null before the value is inserted into the database | |
* | |
* Implement the nullable() method and define an array of attribute names that need to be cast to null if they're empty | |
* | |
* @package App\Models | |
*/ | |
trait NullIfEmptyTrait | |
{ | |
/** | |
* Define the attributes that need to be checked for null values | |
* | |
* @return array | |
*/ | |
abstract public function nullable(); | |
public static function bootNullIfEmptyTrait() | |
{ | |
static::saving(function($item) { | |
foreach ($item->nullable() as $attribute) { | |
$item->attributes[$attribute] = $item->setNullIfEmpty($item->attributes[$attribute]); | |
} | |
}); | |
} | |
/** | |
* Sniff the value and cast to null if conditions are met | |
* | |
* @param mixed $value | |
* @return mixed | |
*/ | |
public function setNullIfEmpty($value) | |
{ | |
$tmpValue = trim($value); | |
return $tmpValue == '' ? null : $value; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment