Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting dates as nullable in laravel

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?

like image 489
Tanmay Avatar asked Feb 22 '18 10:02

Tanmay


2 Answers

Try to do this:

public function setCalledAtAttribute($date)
{
    $this->attributes['called_at'] = empty($date) ? null : Carbon::parse($date);
}
like image 51
Alexey Mezenin Avatar answered Oct 18 '22 21:10

Alexey Mezenin


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; 
like image 34
Khalid Dabjan Avatar answered Oct 18 '22 20:10

Khalid Dabjan