0
  • Laravel 8

I have seen a few of these questions, but the answers are either msising, not for php, or some weird hack.

I have a table in the database, mariadb, with the field type of LONGTEXT - equates to JSON field.

in my model I do:

protected $casts = [
    'event_data'  => 'array',
];

public function setEventDataAttribute($value) {
    $this->attributes['event_data'] = json_encode($value);
}

The data going into the field is:

array:12 [
  "start" => "2022-08-23T00:00:00+00:00"
  "end" => "2022-08-23T00:00:00+00:00"
  "all_day" => false
  "unassigned" => true
  "draft" => true
  "title" => "ggggg"
  "notes" => "test"
  "active" => true
  "schedule_calendar_id" => null
  "jobcode_id" => 122723308
  "customfields" => array:2 [
    1782352 => "Dirty"
    1782354 => "Vacant"
  ]
  "color" => "#888888"
]

When I run json_encode($value) where $value is the above array, I get:

{
    "start": "2022-08-23T00:00:00+00:00",
    "end": "2022-08-23T00:00:00+00:00",
    "all_day": false,
    "unassigned": true,
    "draft": true,
    "title": "ggggg",
    "notes": "test",
    "active": true,
    "schedule_calendar_id": null,
    "jobcode_id": 122723308,
    "customfields": {
        "1782352": "Dirty",
        "1782354": "Vacant"
    },
    "color": "#888888"
}

which according to every validator out there, this is valid JSON. How ever attempting to set this as the attribute into the field throws:

Malformed UTF-8 characters, possibly incorrectly encoded

I can, above the $this->attributes['event_data'] do:

dump(json_encode($value), json_decode(json_encode($value)));

And get the json object listed above and get a stdClass class object of the decoded json.

So my question is:

If the online JSON formatters are saying this is valid JSON, php has no issue encoding and decoding it - why can't laravel insert it? Is it the dates? they must be in ISO8601 Format.

What is going on? I have done this, json encoding like this, a thousand times with no issue.

TheWebs
  • 12,470
  • 30
  • 107
  • 211
  • It's an encoding issue not linked to the validity of the json, check the encoding of the table, it should be something like utf8mb4 – Lk77 Aug 23 '22 at 21:52
  • @Lk77 its utf8mb4_bin. Is there some other format it should be in, there's no utf8mb4, the closest is _bin. – TheWebs Aug 23 '22 at 22:06
  • I would try with utf8mb4_unicode_ci or utf8mb4_general_ci just in case if you have it – Lk77 Aug 23 '22 at 22:13
  • @Lk77 I'll try that, but any particular reason whyother JSON fields created using laravel migrations are set to utf8mb4_bin and they have no issue? - curious cat here. it's why I think theres an issue with the json or something – TheWebs Aug 23 '22 at 22:18

0 Answers0