Home > Enterprise >  Laravel array to string conversion (API store in DATABASE) Json
Laravel array to string conversion (API store in DATABASE) Json

Time:05-22

When I get info from API and want to fill it in my database, I get an error:

array to string conversion

Note: My table is json type for array from database.

Controller:

    public function fetch()
    {

        $response = Http::get('some api');
        $countries = json_decode($response, true);


        foreach ($countries as $country)
        {
            $api = new Country();
            $api['code'] = $country['code'];
            $api['name'] = ['en' => $country['name']['en'], 'ka' => $country['name']['ka']];

            $api->save();
        }

        return 'DONE';
    }

I laso tried otherwise, like, json_decode($reponse->body()) and then $api->name = $country->name->en and etc...

CodePudding user response:

I believe that this save handling alternative should work:

foreach ($countries as $country)
{
    $api = new Country();
    $api->code = $country['code'];
    $api->name = json_encode(['en' => $country['name']['en'], 'ka' => $country['name']['ka']]);

    $api->save();
}
  • Related