I have a form that I'd like to allow the user to enter values that will be parsed by Carbon::Parse(). The fields are validating fine as dates. My model has several date fields in it, and right now I'm doing the following to perform the update:
$fields = $request->all();
if(!empty($fields['date1'])) {
$fields['date1'] = Carbon::parse($fields['date1']);
}
...
$model->save($fields);
This to me seems very inefficient and I feel like the Eloquent model should be able to handle this with just a simple:
$model->save($request->all());
but if the dates aren't formatted in YYYY-MM-DD then it fails, even though it passes the date validation.
I was thinking maybe the best plan would be to do something like this in the model:
public function setDate1Attribute($value) {
$this->attributes['date1'] = Carbon::parse($value);
}
Alternatively I thought about overriding Model::asDateTime() and replacing the Carbon::createWithFormat() call with Carbon::parse().
Any thoughts on this? Are these the best methods, or is there an ever more efficient way?
Thanks!