I am having a hard time understanding the inner workings of date fields in laravel. I have a custom date field named called_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.
protected $dates = ['called_at'];
In order to be able to set it from the controller, via the request('called_at')
input, I would have to set a mutator in the model. So I set one like this:
public function setCalledAtAttribute($date){
$this->attributes['called_at'] = Carbon::parse($date);
}
But the problem is, even if the user does not provide a date in the input field, the called_at
attribute is set to the current timestamp! But I expected it to be NULL.
To get rid of it, I commented out the setCalledAtAttribute
mutator. But now it won't even take the input:
InvalidArgumentException Data missing
Bottom line, how can I set my date field nullable in such a way that when a user leaves the input field blank, the called_at
field wont be set to current timestamp?
Try to do this:
public function setCalledAtAttribute($date)
{
$this->attributes['called_at'] = empty($date) ? null : Carbon::parse($date);
}
If you use parse on an empty string Carbon::parse('')
or null Carbon::parse(null)
Carbon will actually return the current date and time So you should check if $date is provided and not null:
$this->attributes['called_at'] = $date ? Carbon::parse($date); : null;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With