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

martinbean's avatar

Save null timestamp values in an Eloquent model

I have a database table that has a nullable DATETIME column called send_at. In my Eloquent model, I’ve added send_at to the $dates array so that I can call Carbon methods on it in my views.

I also have a corresponding input in my form, but if I pass an empty value Eloquent tries to construct a Carbon instance from it, and fails.

Is there a way to get Eloquent to not try and cast my send_at value to a Carbon instance if it’s empty or null? I’ve tried hooking in to the saving event in the model’s boot() method, and manually setting the attribute to be null, but that doesn’t seem to have an effect.

0 likes
3 replies
juandmegon's avatar

Why not try to use a defualt value, instead of nullable? something like 0000-00-00, could works for you.

mehany's avatar

Use setAttribute and getAttribute methods!

 /**
 * @param $completed_date
 * @return string
 */
// This is the format I diplay in the front-end Y-m-d, change this to your liking
public function setCompletedDateAttribute($completed_date){
    return $this->attributes['completed_date'] = ($completed_date != '')?
        Carbon::createFromFormat('Y-m-d', $completed_date)->format('Y-m-d G:i:s'): NULL;
}

/**
 * @param $completed_date
 * @return string
 */
public function getCompletedDateAttribute($completed_date){
    return ($completed_date != null)?   Carbon::parse($completed_date)->format('Y-m-d') : NULL;
}

Please or to participate in this conversation.