Can#39;t json_encode() an array or Laravel collection: quot;Type is not supportedquot;(无法 json_encode() 数组或 Laravel 集合:“不支持类型)
问题描述
我不知道我做错了什么,因为它适用于应用程序中的所有其他模型.我多次刷新并重新播种数据库.这些模型扩展了相同的抽象方法.
I don't know what I'm doing wrong since it works with all the other models in the app. I refreshed and reseeded the database multiple times. The models extend the same abstract methods.
这是控制器中的代码:
$substrates = $this->substrates->all()->toArray();
$temp = json_encode($substrates);
dd($temp, json_last_error(), json_last_error_msg(), $substrates);
这是 dd() 输出:
This is the dd() output:
false
8
"Type is not supported"
array:119 [▼
0 => array:21 [▼
"id" => 1
"name" => "Wood Free"
"machine_id" => 2
"classification" => "Cover"
"origins" => "Coming Soon"
"duplex" => true
"color" => "Translucents"
"texture" => "Leather"
"finish" => "Felt"
"product_type" => "Sheet"
"caliper" => "0.06"
"m_weight" => 70
"width" => "46.40"
"height" => "32.00"
"pic" => stream resource @17 ▶}
"price" => "0.30"
"created_by" => 38
"updated_by" => 16
"deleted_at" => null
"created_at" => "2018-01-27 08:00:11"
"updated_at" => "2018-01-27 08:00:11"
]
1 => array:21 [▶] ....
当我使用 JSON_PARTIAL_OUTPUT_ON_ERROR 时,我得到一个 json 字符串.
When I use JSON_PARTIAL_OUTPUT_ON_ERROR I get a json string.
推荐答案
错误的原因是你在 pic
中存储了一个 stream 资源无法序列化为 JSON 的序列化对象的字段.
The reason for the error is the fact, that you're storing a stream resource in pic
field of the serialised object that can't be serialised to JSON.
您可以通过在模型中设置 $hidden
属性来告诉 Eloquent 模型在将所选属性转换为数组时跳过它们:
You can tell Eloquent model to skip selected attributes when they're converted to an array by setting a $hidden
attribute in your model:
class Substrate extends Model {
protected $hidden = ['pic'];
}
这篇关于无法 json_encode() 数组或 Laravel 集合:“不支持类型"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:无法 json_encode() 数组或 Laravel 集合:“不支持类型"
基础教程推荐
- 在 yii2 中迁移时出现异常“找不到驱动程序" 2022-01-01
- Doctrine 2 - 在多对多关系中记录更改 2022-01-01
- phpmyadmin 错误“#1062 - 密钥 1 的重复条目‘1’" 2022-01-01
- PHP 守护进程/worker 环境 2022-01-01
- 使用 PDO 转义列名 2021-01-01
- HTTP 与 FTP 上传 2021-01-01
- 如何在 Symfony 和 Doctrine 中实现多对多和一对多? 2022-01-01
- 找不到类“AppHttpControllersDB",我也无法使用新模型 2022-01-01
- 在 CakePHP 2.0 中使用 Html Helper 时未定义的变量 2021-01-01
- 如何在 XAMPP 上启用 mysqli? 2021-01-01