Created
May 19, 2016 10:29
-
-
Save lfarkas/4fc2a8f51e4a283f9f3266223cd729ce to your computer and use it in GitHub Desktop.
NullableFields trait for Laravel 5
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 | |
namespace App; | |
use Illuminate\Database\Eloquent\Model; | |
/** | |
* Use this trait if you some of the fields could be converted to null | |
* automatically if they are empty. | |
* In the Model class $nullable properties should have to be defined as: | |
* | |
* protected static $nullable = []; | |
*/ | |
trait NullableFields | |
{ | |
// /** | |
// * The attributes that should be convert to null in case of empty imput. | |
// * | |
// * @var array | |
// */ | |
// protected static $nullable = []; | |
/** | |
* Boot the nullable fields trait for a model. | |
* | |
* @return void | |
*/ | |
protected static function bootNullableFields() | |
{ | |
static::saving(function (Model $model) { | |
$model->setNullables(); | |
}); | |
} | |
/** | |
* Set empty nullable fields to null. | |
* | |
* @return void | |
*/ | |
protected function setNullables() | |
{ | |
foreach ($this->nullable as $field) { | |
if (!is_numeric($this->attributes[$field]) && empty($this->attributes[$field])) { | |
$this->attributes[$field] = null; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment