laravel变异日期仅适用于api电话

时间:2016-07-18 18:41:15

标签: laravel laravel-5.2

使用laravel 5.2,我有一个基于Web的应用程序并提供API。使用令牌保护对API请求进行身份验证,而使用会话保护对Web请求进行身份验证。我希望能够改变日期,以便它们作为API调用的unix时间戳和Web调用的默认日期字符串(Y-m-d)返回。我能够提出的最好的方法是为API调用提供单独的模型,但我很快发现这会导致多态关系出现问题。有没有人有关于如何实现这一目标的建议?

2 个答案:

答案 0 :(得分:0)

您可以在模型中删除一个函数,该函数将该属性格式化为您希望格式化的方式。

public function formatDateForView()
{
    return date('Y-m-d', $this->attributes['your_timestamp_field']);
}

在您看来,只需在需要时调用它。

{{ $yourModel->formatDateForView(); }}

答案 1 :(得分:0)

您可以使用序列化到JSON添加一个新属性,该属性将按照您希望的方式提供日期格式。

https://laravel.com/docs/master/eloquent-serialization#appending-values-to-json

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class MyModel extends Model
{

    protected $appends = ['my_date'];

    /**
     * Format date for API calls.
     *
     * @return string
     */
    public function getMyDateAttribute()
    {
        return $this->attributes['created_at'] == // format Carbon date here.
    }
}

然后你将在API调用返回的JSON中有一个新的my_date属性。