$object->fill(post()) not working with blank date inputs in OctoberCMS

- 1 answer

Ad

I've got a form that includes some date-type inputs:

<input name="some_date" type="date" />

These fields are not required and may be left unchanged, so the some_date field is set up as "nullable" in the database. Here is the line from the migration file in plugins/acme/plugin/updates/:

$table->date('some_date')->nullable();

The issue is that when I attempt to save the form data using Eloquent's fill() method and OctoberCMS's post() helper I get SQL telling me that I have an "Incorrect date value:''".

$object = new SomeObject();
$object->fill(post());
$object->save();

Of course, I know an empty string is an invalid format but shouldn't doing this work? Should post() not be taking care of this? Or is there an additional setting/var I need to be passing in?

Otherwise I will just need to loop through post() and deal with the empty stings myself. A bit messy.

Ad

Answer

Ad

On second thought, using array_filter() is not a good idea.

What if your model has attributes with falsy values like is_active = false ?

$data = post();

if(is_array($data) && count($data)){

    $data = array_filter($data);
    $object = new SomeObject();
    $object->fill($data);
    $object->save();

}

// $data  = [
//    'some_date' => ''       // false
//    'is_active' => false   // Will be filtered out
// ];

Betters ways i could think of ;

Use the Nullable Trait in your model :

class MyModel extends Model
{
    use \October\Rain\Database\Traits\Nullable;

    protected $nullable = ['some_date'];
}

Now if some_date = '' then it will be nullified.

Or

Use the beforeValidate(), beforeSave() model events and check if some_date is an empty string and set it manually to NULL

public function beforeValidate()
{

    if(empty($this->some_date)){

        $this->some_date = null;

    }

}

Or

Define a Mutator method in your model and manipulate the attribute's value :

protected $dates = ['some_date'];

public function setSomeDateAttribute($value)
{

    if(empty($value)){
        $this->attributes['some_date'] = null;
    }  else  {
        $this->attributes['some_date'] = $value;
    }

}
Ad
source: stackoverflow.com
Ad