Last active
December 6, 2016 09:10
-
-
Save lfarkas/197c9c19a2583737662d4fa5490a9dd4 to your computer and use it in GitHub Desktop.
Nullable value in Laravel 5 field value from HTML form. Until this bug is fixed: https://github.com/laravel/framework/issues/13613 you can overrides Model's asDateTime or use $this->attributes[$field] in stead of $this->{$field}
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; | |
class BaseModel extends Model | |
{ | |
/** | |
* Fields which have to be convert to null in case of empty imput. | |
*/ | |
protected $nullable = []; | |
/** | |
* Listen for save event. | |
*/ | |
protected static function boot() | |
{ | |
parent::boot(); | |
static::saving(function ($model) { | |
$model->setNullables(); | |
}); | |
} | |
/** | |
* Set empty nullable fields to null. | |
* | |
* @param object $model | |
*/ | |
protected function setNullables() | |
{ | |
foreach ($this->nullable as $field) { | |
if (!is_numeric($this->attributes[$field]) && empty($this->attributes[$field])) { | |
$this->attributes[$field] = null; | |
} | |
} | |
} | |
// /** | |
// * Return a timestamp as DateTime object. | |
// * | |
// * @param mixed $value | |
// * @return \Carbon\Carbon | |
// */ | |
// protected function asDateTime($value) | |
// { | |
// if (empty($value)) | |
// return null; | |
// return parent::asDateTime($value); | |
// } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment