Location
Directory: app/Services/Location/
Auto-detects the user's country using weighted scoring from multiple signals — phone code, browser language, timezone, and IP.
Overview
The AutoDetectService combines four signals to determine the most likely 3-letter country code (e.g., IDN, MYS, SGP). Each signal has a weight that contributes to the final score. The country with the highest total score wins.
Why It Exists
Without this service, the application would need the user to manually select their country on every form. This service pre-fills the country field with a best guess, reducing friction in multi-country deployments.
Algorithm — Weighted Scoring
Phone code ─── 40% ──┐
Browser lang ─── 30% ──┤──► Total score ──► Highest wins
Timezone ─── 20% ──┘| Signal | Weight | Source | Example |
|---|---|---|---|
| Phone code | 40% | Request input phone | +62 → IDN |
| Browser language | 30% | Accept-Language header | id-ID → IDN |
| Timezone | 20% | timezone cookie | Asia/Jakarta → IDN |
Scoring Details
Phone code (40%): Extracts the first 3 digits from the submitted phone number and matches against the phone_code column in the countries table.
Browser language (30%): Parses the Accept-Language header:
- Exact region match (e.g.,
id-ID→ regionID→ resolves toIDN) → +30 - Language-only match (e.g.,
id→ maps toIDvialanguageToIso2()) → +20
Timezone (20%): Reads the timezone cookie and maps it via timezoneToCountry():
Asia/Jakarta,Asia/Makassar, etc. →IDNAsia/Kuala_Lumpur→MYSAsia/Singapore→SGP
Fallback
If no signals produce a confident match (total score ≤ 0), or the countries table is empty, the service returns IDN (Indonesia) as the default.
How to Use
use App\Services\Location\AutoDetectService;
use Illuminate\Http\Request;
$detector = app(AutoDetectService::class);
$countryCode = $detector->detect($request);
// Returns: 'IDN', 'MYS', 'SGP', etc.The service is registered as a singleton so the country index is built once per request:
// In a service provider
$this->app->singleton(AutoDetectService::class);Key Files
| File | Purpose |
|---|---|
app/Services/Location/AutoDetectService.php | Weighted country detection using phone, language, timezone |
app/Models/Geographic/Country/Country.php | Countries table — stores code, iso2, phone_code |