无法 json_encode() 数组或 Laravel 集合:“不支持类型"

2021-12-26 00:00:00 json php laravel laravel-5 eloquent

我不知道我做错了什么,因为它适用于应用程序中的所有其他模型.我多次刷新并重新播种数据库.这些模型扩展了相同的抽象方法.

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'];
}

相关文章