Munther Jaber
Munther Jaber

Reputation: 964

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.

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.

Upvotes: 3

Views: 4067

Answers (1)

jedrzej.kurylo
jedrzej.kurylo

Reputation: 40919

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

Upvotes: 6

Related Questions