碳对象在什么时候转向拉拉维尔(Laravel)中的字符串?
我想用Laravel编写类似于碳日期的铸件,我意识到,当碳日期传递到前端或叶片组件时,碳日期已转换为字符串。
我一直在没有运气的情况下挖掘源代码,有人知道这是如何工作的吗?
我的理解是,__tostring()方法在某个时候在碳对象上调用,但不知道在哪里。
一个例子是:
$user = User::first();
// here created_at is a Carbon instance
return response()->with(['created_at' => $user->created_at]);
//once this is on blade created_at is a string
Looking to write a cast similar to Carbon dates with Laravel, I realized that a Carbon date is converted to a string when passed over to the front-end or blade component.
I have been digging the source code with no luck, does anybody know how this works?
My understanding is that the __toString() method is called on the carbon object at some point but don't know where.
an example would be:
$user = User::first();
// here created_at is a Carbon instance
return response()->with(['created_at' => $user->created_at]);
//once this is on blade created_at is a string
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
因此,经过更多的挖掘发现JSON_ENCODE()对此负责。
因此,如果您是json_encode碳对象,则输出为字符串。响应在Laravel的响应过程中转换为JSON。
如果您想通过响应传递PHP对象,并且只想接收一个字符串而不是一个对象,则可以使用
jsonserializable
希望这对将来有帮助
So after more digging found out that json_encode() is responsible for this.
Therefore if you a json_encode a carbon object, the output is a string. The responses are converted to JSON in laravel's ResponseFactory.
If you would like to pass a PHP object through a response and would like to only receive a string instead of an object you can utilize
JsonSerializable
Hope this helps someone in the future