Search code examples
phparraysjsonlaraveljsondecoder

Laravel JSON to Array


I have to convert json to arry from the laravel notifications table data field,

This is the the data shown on dd($user->notifications);

enter image description here

This is how the response shows in the postman enter image description here

I need to show the payload within [] as below

 {
    "payload": [ {
        "title": "PHP Developer Accepted",
        "description": "<p>This is a professional IT Job&nbsp;</p>",
        "user_id": 54,
        "job_id": "01"
    }],
    "message": "",
    "result": true
}

Here's my controller index function

protected function index()
{
    $user = DeviceAuthenticator::getUserByAccessToken();

    foreach ($user->notifications as $notification) {
        $notifications = $notification->data;
    }

    return response()->apiSuccess($notifications); 
}

But before I dump the $notifications before response it shows as an array

dd($notifications);

enter image description here


Solution

  • just wrap in [] your variable which will be like

    protected function index()
    {
        $user = DeviceAuthenticator::getUserByAccessToken();
    
        foreach ($user->notifications as $notification) {
            $notifications = $notification->data;
        }
    
        return response()->apiSuccess([$notifications]);  // wrap in array
    }
    
    

    You may need something like this

    protected function index()
    {
        $user = DeviceAuthenticator::getUserByAccessToken();
    
        $notifications = [];
        foreach ($user->notifications as $notification) {
            $notifications[] = $notification->data;
        }
    
        return response()->apiSuccess($notifications);
    }
    

    here notifications is an array