Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

jgravois's avatar

Null Value for Date blocks insert

I have a form where a date (dob) may or may be known by the HR department at the time a record is created.

I am using the following in the model but the insert is still blocked with a

InvalidArgumentException in Carbon.php line 425:
Unexpected data found.
Unexpected data found.
Unexpected data found.
Data missing

error.

public function setDobAttribute($value)
    {
        if(!$value) {
            $this->attributes['dob'] = null;
        }

        $this->attributes['dob'] = Carbon::createFromFormat('Y-m-d H:i:s', $value);
    }
0 likes
5 replies
spekkionu's avatar

If the value is falsey you are setting dob to null then trying to parse null as a date.

The last line in your mutator method should be in an else block or you should return before reaching it.

jgravois's avatar

I added the return and the error remains

public function setDobAttribute($value)
    {
        if(!$value || $value == null) {
            $this->attributes['dob'] = null;
            return;
        }

        $this->attributes['dob'] = Carbon::createFromFormat('Y-m-d H:i:s', $value);
    }
spekkionu's avatar

What is being passed to the model?

It looks like carbon doesn't see it as a string with the format you specified.

spekkionu's avatar
Level 48

Converting to a carbon instance shouldn't be necessary to save to the db. Try something like this.

public function setDobAttribute($value)
{
    if (empty($value)) {
        $value = null;
    }
    $this->attributes['dob'] = $value;
}
1 like

Please or to participate in this conversation.