duanqun9740
duanqun9740
2015-10-27 09:24

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 doulu7174 5年前

    With laravel 5.2 there's no need for this

    点赞 评论 复制链接分享
  • doulun1915 doulun1915 5年前

    So far as I know , in Laravel 5.1 , what you should do is to add the following code to your model which contains the field 'activated_at'.

    protected $dates=['activated_at'];
    

    And you do not need any getter methods to get a carbon object,you could call the funciton of it directly in your controller.Take User model for example:

    User::findOrFail(1)->activated_at->diffForHumans();
    
    点赞 评论 复制链接分享