Home > Blockchain >  Why it shows Cannot access offset of type string on string error?
Why it shows Cannot access offset of type string on string error?

Time:05-06

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?

CodePudding user response:

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.

  • Related