简体   繁体   中英

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

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...

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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM