Laravel使用Eloquent返回JSON时报Type is not supported错误如何解决
问题根因说明
- 你设置
public $timestamps = false不生效,是因为该配置仅控制Laravel原生的created_at/updated_at两个自动维护的时间字段,对你自定义的timestamp字段无效 - 后续修改代码返回false的原因:
get()->toJson()在遇到无法序列化的资源类型timestamp字段时执行失败返回false,你再对布尔值false执行json_encode()就会得到字符串"false",也就是你看到的返回结果
解决方案
方案1:模型层配置隐藏/转换timestamp字段(推荐,全局生效)
在UserSecurity模型中添加$hidden属性,把timestamp字段加入隐藏列表,序列化时会自动过滤:
protected $hidden = ['timestamp'];
如果需要保留该字段但转成可读格式,可以添加$casts配置,把资源类型转成字符串:
protected $casts = [ 'timestamp' => 'datetime:Y-m-d H:i:s', // 其他字段的转换规则 ];
配置完之后你的原有控制器代码就可以正常运行:
public function find($userName){ $user = UserSecurity::where('userName', $userName)->get(); return response()->json(['data' => $user], 200); }
方案2:查询时指定返回字段(单次查询生效)
查询时通过select方法排除timestamp字段,避免拿到无法序列化的资源内容:
public function find($userName){ $user = UserSecurity::where('userName', $userName) ->select('id', 'userName', /* 其他你需要返回的字段,不要写timestamp */) ->get(); return response()->json(['data' => $user], 200); }
方案3:拿到集合后手动处理字段
如果你确实需要保留timestamp字段的值,可以遍历集合转换资源类型后再返回:
public function find($userName){ $user = UserSecurity::where('userName', $userName)->get()->map(function ($item) { // 把timestamp资源转成字符串,根据你的实际资源格式调整读取逻辑 $item['timestamp'] = (string)$item['timestamp']; return $item; }); return response()->json(['data' => $user], 200); }
内容的提问来源于stack exchange,提问作者mar fo
相关产品推荐
相关产品推荐

