PHP code example of maxiewright / laravel-tt-addresses

1. Go to this page and download the library: Download maxiewright/laravel-tt-addresses 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/ */

    

maxiewright / laravel-tt-addresses example snippets


use MaxieWright\TrinidadAndTobagoAddresses\Database\Seeders\DivisionSeeder;
use MaxieWright\TrinidadAndTobagoAddresses\Database\Seeders\CitySeeder;

public function run(): void
{
    $this->call([
        DivisionSeeder::class,
        CitySeeder::class,
        // ... your other seeders
    ]);
}

return [
    // Customise table names if they conflict with existing tables
    'tables' => [
        'divisions' => 'tt_divisions',
        'cities' => 'tt_cities',
    ],

    // ISO country code
    'country_code' => 'TT',
];

use MaxieWright\TrinidadAndTobagoAddresses\Models\Division;
use MaxieWright\TrinidadAndTobagoAddresses\Models\City;
use MaxieWright\TrinidadAndTobagoAddresses\Enums\DivisionType;

// Get all divisions
$divisions = Division::all();

// Get only Trinidad divisions
$trinidadDivisions = Division::trinidad()->get();

// Get only Tobago
$tobago = Division::tobago()->first();

// Get divisions by type
$boroughs = Division::ofType(DivisionType::Borough)->get();
$regionalCorporations = Division::ofType(DivisionType::RegionalCorporation)->get();

// Get all cities in a division
$chaguanasCities = Division::where('abbreviation', 'CHA')
    ->first()
    ->cities;

// Find a city
$portOfSpain = City::where('name', 'Port-of-Spain')->first();
$portOfSpain->division->name; // "Port of Spain"
$portOfSpain->island; // "Trinidad"

// Get full location string
$city = City::where('name', 'Scarborough')->first();
$city->full_location; // "Scarborough, Tobago"

use MaxieWright\TrinidadAndTobagoAddresses\Enums\DivisionType;

$type = DivisionType::RegionalCorporation;
$type->label();  // "Regional Corporation"
$type->island(); // "Trinidad"

// Filament support
$type->getLabel(); // "Regional Corporation"

use Illuminate\Database\Eloquent\Model;
use MaxieWright\TrinidadAndTobagoAddresses\Concerns\HasTrinidadAndTobagoAddress;

class Customer extends Model
{
    use HasTrinidadAndTobagoAddress;

    protected $fillable = [
        'name',
        'address_line_1',
        'address_line_2',
        'division_id',
        'city_id',
    ];
}

Schema::create('customers', function (Blueprint $table) {
    $table->id();
    $table->string('name');
    $table->string('address_line_1')->nullable();
    $table->string('address_line_2')->nullable();
    $table->foreignId('division_id')
          ->nullable()
          ->constrained(config('laravel-tt-addresses.tables.divisions'))
          ->nullOnDelete();
    $table->foreignId('city_id')
          ->nullable()
          ->constrained(config('laravel-tt-addresses.tables.cities'))
          ->nullOnDelete();
    $table->timestamps();
});

$customer = Customer::create([
    'name' => 'John Doe',
    'address_line_1' => '123 Main Street',
    'division_id' => 11, // Chaguanas
    'city_id' => 88,     // Chaguanas city
]);

$customer->division->name;       // "Chaguanas"
$customer->city->name;           // "Chaguanas"
$customer->formatted_address;    // "123 Main Street, Chaguanas, Chaguanas"
$customer->island;               // "Trinidad"

use MaxieWright\TrinidadAndTobagoAddresses\Models\City;

// Get coordinates
$city = City::where('name', 'Port-of-Spain')->first();
$city->latitude;    // 10.6596
$city->longitude;   // -61.5086
$city->coordinates; // ['latitude' => 10.6596, 'longitude' => -61.5086]

// Calculate distance between cities (in kilometers)
$pos = City::where('name', 'Port-of-Spain')->first();
$sfo = City::where('name', 'San Fernando')->first();
$distance = $pos->distanceTo($sfo); // ~47km

// Find cities within 20km of a point
$nearbyCities = City::query()
    ->withinRadius(10.6596, -61.5086, 20)
    ->get();

// Find the nearest city to coordinates
$nearest = City::findNearest(10.5, -61.4);

// Order cities by distance from a point
$cities = City::query()
    ->orderByDistanceFrom(10.6596, -61.5086)
    ->take(10)
    ->get();

// Get map URLs
$city->getGoogleMapsUrl();      // https://www.google.com/maps?q=...
$city->getOpenStreetMapUrl();   // https://www.openstreetmap.org/?mlat=...

$customer = Customer::find(1);

// Get coordinates from associated city
$customer->coordinates;  // ['latitude' => ..., 'longitude' => ...]
$customer->latitude;
$customer->longitude;

// Check if has coordinates
if ($customer->hasCoordinates()) {
    // Calculate distance to another customer
    $distance = $customer->distanceTo($otherCustomer);
    
    // Find nearby cities
    $nearbyCities = $customer->findNearbyCities(radiusKm: 15, limit: 5);
}

use MaxieWright\TrinidadAndTobagoAddresses\Models\City;

// Fast autocomplete search (optimized for prefix matching)
$results = City::autocomplete('Port', limit: 5)->get();
// Returns cities starting with "Port" (like "Port of Spain")

// Convert to API format
$searchResults = $results->map->toSearchResult();
// [
//   'id' => 1,
//   'name' => 'Port of Spain',
//   'division' => 'Port of Spain',
//   'full_location' => 'Port of Spain, Port of Spain',
//   'island' => 'Trinidad',
//   'coordinates' => ['latitude' => 10.6596, 'longitude' => -61.5089],
//   'division_type' => 'City Corporation'
// ]

// Convert to autocomplete options
$options = $results->map->toAutocompleteOption();
// [
//   'value' => 1,
//   'label' => 'Port of Spain', 
//   'description' => 'Port of Spain, Trinidad',
//   'coordinates' => ['latitude' => 10.6596, 'longitude' => -61.5089]
// ]

// Get popular/major cities (configured in config file)
$popular = City::popular()->get();

// With caching (recommended for production)
$popularCached = City::getPopularCached(ttl: 3600); // Cache for 1 hour

use MaxieWright\TrinidadAndTobagoAddresses\Enums\SearchRadius;

// Find cities within predefined search radii
$walking = City::withinSearchRadius($lat, $lng, SearchRadius::WALKING)->get();     // 2km
$driving = City::withinSearchRadius($lat, $lng, SearchRadius::DRIVING)->get();     // 10km  
$regional = City::withinSearchRadius($lat, $lng, SearchRadius::REGIONAL)->get();   // 25km
$islandWide = City::withinSearchRadius($lat, $lng, SearchRadius::ISLAND_WIDE)->get(); // 100km

// Search radius labels for UI
SearchRadius::WALKING->label();      // "2 km (Walking Distance)"
SearchRadius::DRIVING->description(); // "Short drive, local area"

// Get suggested nearby cities for any location
$suggestions = City::getSuggestedNearbyCities(
    latitude: 10.6596,
    longitude: -61.5089, 
    maxCities: 10
);

// Clear and warm search caches
php artisan tt-addresses:optimize-search --clear-cache --warm-cache

// Or just optimize (clear + warm)
php artisan tt-addresses:optimize-search

return [
    // ... existing config ...
    
    'search' => [
        'autocomplete_limit' => 10,           // Max results for autocomplete
        'cache_ttl' => 900,                   // 15 minutes
        'popular_cities_cache_ttl' => 3600,   // 1 hour
    ],
    
    'popular_cities' => [
        'Port of Spain',
        'San Fernando', 
        'Chaguanas',
        'Arima',
        'Point Fortin',
        'Couva',
        'Sangre Grande',
        // ... add your most searched cities
    ],
];

use Filament\Forms\Components\Select;
use MaxieWright\TrinidadAndTobagoAddresses\Models\Division;
use MaxieWright\TrinidadAndTobagoAddresses\Models\City;

// Division select
Select::make('division_id')
    ->label('Division')
    ->options(Division::pluck('name', 'id'))
    ->searchable()
    ->preload()
    ->live(),

// City select (filtered by division)
Select::make('city_id')
    ->label('City/Town/Village')
    ->options(function (callable $get) {
        $divisionId = $get('division_id');
        if (!$divisionId) {
            return City::pluck('name', 'id');
        }
        return City::where('division_id', $divisionId)
            ->pluck('name', 'id');
    })
    ->searchable()
    ->preload(),

use Filament\Tables\Filters\SelectFilter;
use MaxieWright\TrinidadAndTobagoAddresses\Enums\DivisionType;

SelectFilter::make('type')
    ->options(DivisionType::class),
bash
php artisan tt-addresses:install
bash
php artisan db:seed --class="MaxieWright\TrinidadAndTobagoAddresses\Database\Seeders\DivisionSeeder"
php artisan db:seed --class="MaxieWright\TrinidadAndTobagoAddresses\Database\Seeders\CitySeeder"