无法json_encode()一个数组或Laravel集合:“不支持类型” [英] Can't json_encode() an array or Laravel collection: "Type is not supported"
问题描述
我不知道我在做什么错,因为它可以与应用程序中的所有其他模型一起使用。我刷新并重新播种了数据库多次。这些模型扩展了相同的抽象方法。
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()的输出:
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字符串。 / p>
When I use JSON_PARTIAL_OUTPUT_ON_ERROR I get a json string.
推荐答案
出现错误的原因是,您在流资源中存储了无法序列化为JSON的序列化对象的code> pic 字段。
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.
您可以告诉Eloquent模型跳过选定的对象通过在模型中设置 $ hidden
属性将它们转换为数组时的属性:
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集合:“不支持类型”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!