Can't json_encode() an array or Laravel collection: “Type is not supported”

那年仲夏 提交于 2020-06-23 08:18:33

问题


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.

This is the code in the controller:

$substrates = $this->substrates->all()->toArray();
$temp = json_encode($substrates);
dd($temp, json_last_error(), json_last_error_msg(), $substrates);

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 [▶] ....

When I use JSON_PARTIAL_OUTPUT_ON_ERROR I get a json string.


回答1:


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.

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


来源:https://stackoverflow.com/questions/48487030/cant-json-encode-an-array-or-laravel-collection-type-is-not-supported

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!