0

I have json file in folder database\data\countries.json and I have CountriesTableSeeder.php

I want to seed all data in countries.json into my table Country. But it occurs error Trying to get property of non-object

I have followed the step that I found, but I still got an error.

This is my model:

protected $fillable = ['country_name', 'iso_code'];

This is my seeder code:

public function run()
{
  $countryJson = File::get("database/data/countries.json");
  $data = json_decode($countryJson, true);
  foreach ($data as $obj) {
    Country::create(array(
      'country_name' => $obj->name, 'iso_code' => $obj->sortname
    ));
  }
}
Jems
  • 1,666
  • 4
  • 20
  • 50
  • Have you made sure you have the file by testing for the existence of `$countryJson` ? – user10089632 Nov 23 '17 at 04:45
  • Yes, I have @user10089632 If I don't have the file, my command prompt will display error `File does not exist at path database/data/countries.json` – Jems Nov 23 '17 at 04:46
  • You have converted json into arrays, so there would be not objects `$obj->name` – Rafee Nov 23 '17 at 04:48
  • So, what should I do? @Rafee – Jems Nov 23 '17 at 04:49
  • `print_r($data)` then check out. you will findout automaticall. You need to follow @ankit answers, hope that will solve it. – Rafee Nov 23 '17 at 04:50
  • possible duplicate of https://stackoverflow.com/questions/25195010/json-decode-returning-error-notice-trying-to-get-property-of-non-object#25195092 – user10089632 Nov 23 '17 at 04:53
  • How can I check from `print_r`? `php artisan migrate --seed' works in command prompt, not in my UI @Rafee – Jems Nov 23 '17 at 05:03
  • Can you validate json manually, then do `dd($data)` – Rafee Nov 23 '17 at 05:07

1 Answers1

2

You need to pass same variable in foreach, also make sure you have name element by checking dd($data); and you need to get array element by $obj['name'] not by $obj->name as it's not object.

$data = json_decode($countryJson, true);
        foreach ($data['countries'] as $obj) {
            Country::create(array(
              'country_name' => $obj['name'], 'iso_code' => $obj['sortname']
              ));
        }
Jems
  • 1,666
  • 4
  • 20
  • 50
ankit patel
  • 1,888
  • 11
  • 12