app/Console/Commands/Setup/ImportCountries.php
/**
     * Execute the console command.
     *
     * @return mixed
     */
Execute the console command.
@return mixed
Execute the console command . @return mixed
public function handle()
    {
        $this->info('Importing countries into the database...');
        try {
            $filename = resource_path('countries.json');
            if (!file_exists($filename)) {
                throw new FileNotFoundException('Could not find the countries.json file at: '.$filename);
            }
            if (!is_readable($filename)) {
                throw new FileException('The countries.json ('.$filename.') file is not readable by the process.');
            }
            $countries = json_decode(file_get_contents($filename), true);
            foreach ($countries as $country) {
                $this->line('Setting up country: '.$country['name']['common'].'...');
                $model = Country::firstOrNew(['iso_code' => $country['cca2']]);
                $model->name = $country['name']['common'];
                $model->dialing_code = $country['callingCode'][0] ?? null;
                if (!$model->save()) {
                    $this->warn('save failed!');
                    continue;
                }
                $this->line('saved.');
            }
            $this->info('Done!');
        } catch (\Throwable $e) {
            $this->error($e->getMessage());
        }
        return;
    }
public function handle ( ) { $ this -> info ( 'Importing countries into the database...' ) ; try { $ filename = resource_path ( 'countries.json' ) ; if ( ! file_exists ( $ filename ) ) { throw new FileNotFoundException ( 'Could not find the countries.json file at: ' . $ filename ) ; } if ( ! is_readable ( $ filename ) ) { throw new FileException ( 'The countries.json (' . $ filename . ') file is not readable by the process.' ) ; } $ countries = json_decode ( file_get_contents ( $ filename ) , true ) ; foreach ( $ countries as $ country ) { $ this -> line ( 'Setting up country: ' . $ country [ 'name' ] [ 'common' ] . '...' ) ; $ model = Country :: firstOrNew ( [ 'iso_code' => $ country [ 'cca2' ] ] ) ; $ model -> name = $ country [ 'name' ] [ 'common' ] ; $ model -> dialing_code = $ country [ 'callingCode' ] [ 0 ] ?? null ; if ( ! $ model -> save ( ) ) { $ this -> warn ( 'save failed!' ) ; continue ; } $ this -> line ( 'saved.' ) ; } $ this -> info ( 'Done!' ) ; } catch ( \ Throwable $ e ) { $ this -> error ( $ e -> getMessage ( ) ) ; } return ; }
Execute the console command.
Execute the console command .
# get the filename # read in the file data # to see if we already have the model # set the properties