-1

I have a query that returns a specific post:

  $post = Post::where('post_code', $post['post_code'])->first();

And it returns like this:

^ App\Models\Post {#1351 ▼
  #connection: "mysql"
  #table: "hotels"
  ...
  #attributes: array:6 [▼
    "id" => 1
    "post_code" => "AB1"
    "comments" => "[{"key": "1DfsGlyLv3yK1", "layout": "comment", "attributes": {"title": "title 1", "message": "comment 1"}}, {"key": lfhK5Nbwc2cPLKY", "layout": "note", "attributes": {"title": "title 2", "message": "comment 2"}}] ◀"
  ]

And I want to display each comment with its specific title and comment like below:

[
                    'name' => "post_comments",
                    'data' => [
                        'comments' =>
                        collect($post['comments'])->map(function ($comment) {
                            return [
                                'title' => $comment['title'],
                                'message' => $comment['message'],
                            ];
                        }),
                    ]
                ],

However doing like this its showing an error:

Undefined array key "title"

Do you know what can be the issue since the title key exists? Thanks

Bernard
  • 81
  • 8
  • Sorry it was a typo. I updated the question. – Bernard May 05 '22 at 15:39
  • If I understand well, title and message are inside attributes that is inside comments, so you have to follow this order to ger the title. comments->attributes->title/message – Juranir Santos May 05 '22 at 16:01
  • Thanks but like that it shows "Attempt to read property "title" on array". With return [ 'title' => $comment->title, 'message' => $comment->message, ];. – Bernard May 05 '22 at 16:04

1 Answers1

1

I see you just missed one level in comment object:

[
                    'name' => "post_comments",
                    'data' => [
                        'comments' =>
                        collect($post['comments'])->map(function ($comment) {
                            return [
                                'title' => $comment['attributes']['title'],
                                'message' => $comment['attributes']['message'],
                            ];
                        }),
                    ]
                ],
Mesuti
  • 878
  • 1
  • 13
  • 29