Claudio Ludovico Panetta Claudio Ludovico Panetta - 6 days ago 5
PHP Question

Laravel 5.1.x how to manipulate date correctly?

I've a field called

activated_at
and I want to treat it like every other date in Laravel. In the database it's a timestamp and I've insert it inside the
$dates
array along side with the common dates like
updated_at
,
created_at
and
deleted_at
.

Little Side note this is a part of an API system, which doesn't rely on forms and web at all, so I cannot convert the data directly from the view

The problem is that, in order to set and get it properly I've setup two mutators (AKA Getter and Setter).

Current setter, it's not the best solution out there but I honestly don't know how to create a setter that will convert all the data passed into suitable one for the database. I'm using MariaDB

* Automatically parse the date from metric system to
* Imperial system because American DATABASES
*
* @param string $value
*/
public function setActivatedAtAttribute($value)
{
if(!$value instanceof \DateTime)
{
$value = Carbon::createFromFormat('d/m/Y H:i:s', $value)->toDateTimeString();
}
$this->attributes['activated_at'] = $value;
}


Anyways this setters is working quite fine, I've written a bunch of unit tests and I get green on them.

The real problem is the getter, which I though it returns the Carbon instance of the date but instead it simply returns a string

/**
* Return the correct metric format of the date
*
* @param string $value
* @return string
*/
public function getActivatedAtAttribute($value)
{
// Because it's a string we cannot use Carbon methods
// Unless we instantiate a new Carbon object which it stupid
// Since the activated_at field is inside the $dates array
// Shouldn't we get the carbon object automatically?
return $value;
}


My concerns are in the comment block inside the getter method.

That being said, is there a better method to batter handling DateTime using mutators in Laravel 5.1.x? I don't mind to handle ALL date time since
created_at
,
updated_at
and
deleted_at
are already handled behind the curtains

TL;DR


is there a better method to batter handling DateTime using mutators in Laravel 5.1.x? I don't mind to handle ALL date time since
created_at
,
updated_at
and
deleted_at
are already handled behind the curtains

Answer

With laravel 5.2 there's no need for this

Comments