Reputation: 137
I have got a database field containing only a time, it's declared in my migration as
$table->time('time')->default('00:00:00');
Now I want to add a number of seconds to this field using Eloquent, doing something like:
$activetime->time->add(new DateInterval('PT5S'));
(where $activetime is a object of a Eloquent model)
First try on this I got
Call to a member function add() on string
So obviously I have to tell Eloquent that this is not a string but a time. The closest I have got is putting it in protected $dates in the model, but then instead I get
Unexpected data found.
I suspect this is because it isn't really a date but only a time, but I can't seem to find much information about how to handle times. Is there any way of solving this or would I be better off using something else, like dateTime or timestamp (or even an integer for amount of seconds)? What I DO want to record is a users amount of active time for a given date, so for that purpose time seems like the natural choice...
Upvotes: 3
Views: 9144
Reputation: 1151
This is because Laravel reads time
database type as just a string
and you are expecting a DateTime Object
.
Add this to your Eloquent model:
public function getTimeAttribute($value)
{
return new \DateTime($value);
}
You can also cast your time
to DateTime Object
using Laravel Attribute Casting, but you'll have to append some date to your time, because Laravel is expecting correct format
Upvotes: 3