Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Try this:

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading