Laravel自定义属性未突变为Carbon日期 [英] Laravel custom attribute not being mutated to Carbon date

查看:50
本文介绍了Laravel自定义属性未突变为Carbon日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在让Laravel将自定义属性转换为 Carbon 日期时遇到问题.这是一个示例模型:

I'm having problems getting Laravel to cast a custom attribute as a Carbon date. Here's an example model:

class Organisation extends Model
{
    protected $dates = [
        'my_date'
    ];

    public function getMyDateAttribute() 
    {
        return "2018-01-01 00:00:00";
    }
}

我希望将 my_date 强制转换为 Carbon 日期,但是如果我执行 dd($ organisation-> my_date),只是以字符串形式返回日期.

I'd expect my_date to be cast to a Carbon date however if I do dd($organisation->my_date) it just returns the date as a string.

我见过有人建议只从custom属性返回一个 Carbon 实例,这部分起作用, my_date 属性可以用作 Carbon实例,但是如果您随后将模型返回为Json,则会得到以下结果:

I've seen people suggest to just return a Carbon instance from the custom attribute, and this partially works, the my_date attribute is availabe as a Carbon instance within the application, however if you then return the model as Json you end up with:

{
    "name": "Big Business",
    "my_date": {
        "date": "2018-01-01 00:00:00.000000",
        "timezone_type": 3,
        "timezone": "Europe/London"
    }
}

而不是期望的:

{
    "name": "Big Business",
    "my_date": "2018-01-01 00:00:00"
}

还有其他人遇到过这种情况吗?如果可以,您是否找到了解决方案?

Has anyone else come across this and if so have you found a solution?

在进一步调查中,我已经找到了问题所在(但我还没有解决方案).当您返回Eloquent模型时,运行 toJson 方法的 __ toString 魔术方法,并在跟踪链时会序列化 $ dates 中的所有Carbon日期.代码>变量.它也完全跳过了突变属性的序列化,这就是我所看到的.

Upon further investigation I've tracked down the problem (but I don't have a solution yet). When you return an Eloquent model the __toString magic method which runs the toJson method and as you trace down the chain it serializes any Carbon dates in the $dates variable. It also completely skips over this serialization for mutated attributes, which is what I'm seeing.

我需要找到一种方法来序列化被调用 __ toString 时返回 Carbon 日期的突变属性.

I need to find a way to seralize mutated attributes that return a Carbon date when __toString is called.

推荐答案

将您的组织模型编辑为此:

use Carbon\Carbon;
class Organisation extends Model
{


    public function getMyDateAttribute($value) 
    {
        //you can manipulate the date here:
        $date = Carbon::parse($value,config('timezone'));
        return $date;
    }
}

这篇关于Laravel自定义属性未突变为Carbon日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆