'How to properly fix - Cannot use empty array elements in arrays

I have the code below but it showing an error "Cannot use empty array elements in arrays".

It seems that the issue is in this line }), collect(json_decode($post['comments'], true))->map(function ($comment) {

Code:

'data' => [
    'comments' =>
    collect(json_decode($configs['comments'], true))->map(function ($comment) {
        return [
            'title' => $comment['attributes']['title'],
            'message' => $comment['attributes']['message'],
        ];
    }),  collect(json_decode($posts['comments'], true))->map(function ($comment) {
        return [
            'title' => $comment['attributes']['title'],
            'message' => $comment['attributes']['message'],
        ];
    }),
]


Solution 1:[1]

If we simplify your code it seems like this;

'data' => [
    'comments' =>
       collect(),  
       collect()
]

It is not a valid syntax. You can try like this;

$comments = collect(json_decode($configs['comments'], true))->map(function ($comment) {
    return [
        'title' => $comment['attributes']['title'],
        'message' => $comment['attributes']['message'],
    ];
});
$postComments =  collect(json_decode($posts['comments'], true))->map(function ($comment) {
    return [
        'title' => $comment['attributes']['title'],
        'message' => $comment['attributes']['message'],
    ];
});

'data' => [
    'comments' => $comments->merge($postComments)->toArray()
];

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 xuma