duanqun9740 2015-10-27 09:24
浏览 27
已采纳

Laravel 5.1.x如何正确操作日期?

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

  • 写回答

2条回答 默认 最新

  • doulu7174 2016-03-01 09:01
    关注

    With laravel 5.2 there's no need for this

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 有没有帮写代码做实验仿真的
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥30 vmware exsi重置后登不上
  • ¥15 易盾点选的cb参数怎么解啊
  • ¥15 MATLAB运行显示错误,如何解决?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题