Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

skoobi's avatar
Level 13

Using JSON from api

Hi. I'm not sure what i'm doing wrong, but i'm struggling with getting json data used and saved.

What I have is an api call that gets the data returned as csv, I then format it to json so I can grab what I need and save it into the database.

The issue im getting is that I get the json data, but then cannot get any info from it i.e. the id, timestamp etc.

public function formatReportData($reportData)
    {
		$keys = collect(['id', 'timestamp', 'type', 'user']);

        $lines = collect(explode(PHP_EOL, trim($reportData)))
            ->map(function ($line) use ($keys) {
                return $keys->combine(
                    array_map('trim', str_getcsv($line))
                )
                    ->toJson();
            });

        return $lines->all();
}


public function saveReportLines($lines)
    {
        foreach ($lines as $x) {
           dd($x);
			// saveReportLines dump returns:: 
			// "{"id":"9264","timestamp":"2023-01-01 12:00:01","type":"Date Created","user":"System"}"

            ReportImport::create([
                'uuid' => Str::uuid(),
                'name' => 'welcome_stamp',
                'json_data' => $x,
                'status' => 0,
            ]);
			// Saves to db as 
			// "{\"id\":\"9264\",\"timestamp\":\"2023-01-01 12:00:01\",\"type\":\"Date Created\",\"user\":\"System\"}"
        }
    }

Normally, I can do a foreach in a blade view and use $item->json_data->id but it comes up with "Attempt to read property "id" on string". It's saved to the database as JSON, Im struggling with this today, one of those days...

Any help or guidance would be much appreciated.

0 likes
1 reply
skoobi's avatar
Level 13

Eventually solved. It was setting as a JSON when mapping the data.


// From
$lines = collect(explode(PHP_EOL, trim($reportData)))
            ->map(function ($line) use ($keys) {
                return $keys->combine(
                    array_map('trim', str_getcsv($line))
                )
                    ->toJson();
            });

// To
$lines = collect(explode(PHP_EOL, trim($reportData)))
            ->map(function ($line) use ($keys) {
                return $keys->combine(
                    array_map('trim', str_getcsv($line))
                );
            });

Please or to participate in this conversation.