gavinhewitt
5/18/2016 - 10:53 PM

Nullable value in Laravel 5 field value from HTML form. Until this bug is fixed: https://github.com/laravel/framework/issues/13613 you can o

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}

<?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);
    // }
}