Skip to content

Instantly share code, notes, and snippets.

@benrowe
Created December 1, 2015 05:16
Show Gist options
  • Save benrowe/a9d6dd02e057d8795bb7 to your computer and use it in GitHub Desktop.
Save benrowe/a9d6dd02e057d8795bb7 to your computer and use it in GitHub Desktop.
NullIfEmptyTrait for Laravel models
<?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