Laravel model saving dates as null

I have a custom date field named reserved_at and I set it as nullable in the schema. Since it’s a date field, I would naturally want it to be a Carbon instance, so in the model I pushed this attribute to the $dates array. In order to be able to set it from the controller, via the request(‘reserved_at’) input, I would have to set a mutator in the model. So I set one like this:

public function setReserveddAtAttribute($date){
    $this->attributes['reserved_at'] = Carbon::parse($date);
}

How can I set my date field nullable in such a way that when a user leaves the input field blank, the reserved_at field wont be set to current timestamp?

Code block which solving my problem

>Solution :

Try this:

public function setReservedAtAttribute($date)
{
    $this->attributes['reserved_at'] = empty($date) ? null : Carbon::parse($date);
}

Leave a Reply