'Why it shows Cannot access offset of type string on string error?
This dump dd($post['comments']); shows the content below:
^ "[{"key": "o0Gdz1EsxOpOLN", "layout": "comment", "attributes": {"title": "a", "comment": "b"}}]"
Then this data is being transformed like this:
[
'name' => "comments",
'data' => [
'comments' =>
collect($post['comments'])->map(function ($comment) {
return [
'title' => $comment['attributes']['title'],
'message' => $comment['attributes']['message'],
];
}),
]
],
But it shows an error:
Cannot access offset of type string on string
The error seems that its here:
'title' => $comment['attributes']['title'],
Do you know what can be the issue?
Solution 1:[1]
Use json_decode() to access the data.
[
'name' => "comments",
'data' => [
'comments' =>
collect(json_decode($post['comments'], true))->map(function ($comment) {
return [
'title' => $comment['attributes']['title'],
'message' => $comment['attributes']['message'],
];
}),
]
],
But you should test it before hand that the content of $post['comments'] contain the json data structure you need.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | N69S |
