Reputation: 361
I'm trying to save some data to my database and need to format a date/time before the save.
my code is as follows:
public static function toSqlDate($date, $formatResult = true)
{
if (!$date)
{
return null;
}
$dateTime = DateTime::createFromFormat(DEFAULT_DATETIME_FORMAT, $date, new DateTimeZone(DEFAULT_TIMEZONE));
return $formatResult ? $dateTime->format('Y-m-d') : $dateTime;
}
When I try to save I get the following error in the debugger. the return line is the line highlighted as having the error.
Symfony \ Component \ Debug \ Exception \ FatalErrorException
Call to a member function format() on a non-object
I'm not really sure how to even attempt to fix this. Is there a way I can output what each of the values being pulled in are before it throws the error? I'm trying to figure out what $dateTime is not being returned as an object.
any help would greatly be appreciated.
Some additional information:
I have created a utility/alias pointing the the function above and in my model repository I access it via the following.
public function save($publicId, $data)
{
...
$form->date = Utils::toSqlDate($data['date']);
...
$form->save();
...
}
and I have the following field in my view
{{ Former::text('date')->addClass('form-control form-control-inline input-medium default-date-picker')->data_bind("datePicker: date, valueUpdate: 'afterkeydown'") }}
Upvotes: 1
Views: 3445
Reputation: 146201
You may create a mutator
method in your Eloquent Model
to make the conversion automatic when you save any model, for example, if you have a timestamp as dob
in your User
model then just add the following method in your User
model:
public function setDobAttribute($value)
{
$dt = \Carbon\Carbon::createFromFormat('Y/m/d', $value)->toDateString();
$this->attributes['dob'] = $dt;
}
So you can just save a user model easilt, like:
$user = new User;
$user->dob = Input::get('dob');
// ...
$user->save();
The date will be automatically set for you using the mutator/setDobAttribute
method defined in the User
model, you don't need to do anything.
Upvotes: 4