PHP code example of risetechapps / geonames-for-laravel

1. Go to this page and download the library: Download risetechapps/geonames-for-laravel library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

risetechapps / geonames-for-laravel example snippets


use RiseTechApps\Geonames\Features\Country;

$country = new Country('BR');

if ($country->exists()) {
    echo $country->getName();           // Brazil
    echo $country->getEmoji();          // 🇧🇷
    echo $country->getPhoneCode();      // 55
    echo $country->getTimezone();       // America/Sao_Paulo
}

$country = new Country('BR');

// ⚠️ $country->states() retorna um objeto States (repositório)
// Para obter os dados, use ->all()
$states = $country->states()->all();

foreach ($states as $state) {
    echo $state->getName();    // ACRE, ALAGOAS, AMAZONAS...
    echo $state->getIso2();    // AC, AL, AM...
}

// Outros métodos disponíveis
$country->states()->first();              // Primeiro estado
$country->states()->count();              // Total de estados (27)
$country->states()->search('Sao');       // Busca por nome
$country->states()->paginate(20, 1);     // Paginação

use RiseTechApps\Geonames\Features\State;

$country = new Country('BR');
$state = $country->state('SP');  // ou new State('SP', $country)

if ($state->exists()) {
    echo $state->getName();    // SÃO PAULO
    echo $state->getIso2();    // SP
}

$country = new Country('BR');
$state = $country->state('SP');

// ⚠️ $state->cities() retorna um objeto Cities (repositório)
// Para obter os dados, use ->all()
$cities = $state->cities()->all();

foreach ($cities as $city) {
    echo $city->getName();       // SÃO PAULO, CAMPINAS...
    echo $city->getLatitude();   // -23.5475
    echo $city->getLongitude();  // -46.6361
}

// Outros métodos disponíveis
$state->cities()->first();                // Primeira cidade
$state->cities()->count();                // Total de cidades
$state->cities()->search('Santo');      // Busca por nome
$state->cities()->paginate(50, 1);      // Paginação

// Acessar via helper geonames()
$country = geonames()->country('BR');

// Listar todos os países
$countries = geonames()->countries()->all();

// Listar regiões
$regions = geonames()->regioes()->all();

$geonames = geonames();
$geonames->countries()->all();    // Todos os países
$geonames->country('BR');          // País específico
$geonames->regioes()->all();      // Todas as regiões

// ❌ Incorreto: Não retorna dados diretamente
$country->states();           // Retorna objeto States
$state->cities();              // Retorna objeto Cities

// ✅ Correto: Chame ->all() para obter os dados
$country->states()->all();     // Retorna Collection de State
$state->cities()->all();       // Retorna Collection de City

// ✅ Também funciona: Busca específica
$country->state('SP');         // Retorna objeto State
$state->city('São Paulo');     // Retorna objeto City

// No seu Model
use RiseTechApps\Geonames\Traits\HasGeonames;

class User extends Model
{
    use HasGeonames;
}

// Definir localização (com validação automática)
$user->setLocation('BR', 'SP', 'São Paulo');
$user->save();

// Acessar objetos
$user->country(); // Retorna Country|null
$user->state();   // Retorna State|null
$user->city();    // Retorna City|null

// Formatar endereço
$user->getFullAddress('short');  // "São Paulo, SP"
$user->getFullAddress('medium'); // "São Paulo, SÃO PAULO, Brazil"
$user->getFullAddress('long');   // "São Paulo, SÃO PAULO, Brazil 🇧🇷 (America/Sao_Paulo)"

// Verificações
$user->hasLocation();         // Tem pelo menos país?
$user->hasCompleteLocation(); // Tem país, estado e cidade?
$user->getTimezone();         // Fuso horário

// Queries
User::whereCountry('BR')->get();
User::whereState('SP')->get();
User::whereRegion('EUROPE')->get();

// Distância entre usuários
$distance = $user1->distanceTo($user2, 'km');
bash
php artisan geonames:install
bash
# Instalação completa (baixa dados + publica config)
php artisan geonames:install

# Apenas download de dados
php artisan geonames:install-data --countries=BRA,USA

# Pré-aquecer cache (recomendado em produção)
php artisan geonames:cache-warm --country=BRA

# Limpar cache
php artisan geonames:cache-clear

# Benchmark de performance
php artisan geonames:benchmark
bash
# Instalação completa
php artisan geonames:install

# Com migration para um model específico
php artisan geonames:install --model=User --migration