Skip to content

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% ──┘
SignalWeightSourceExample
Phone code40%Request input phone+62IDN
Browser language30%Accept-Language headerid-IDIDN
Timezone20%timezone cookieAsia/JakartaIDN

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 → region ID → resolves to IDN) → +30
  • Language-only match (e.g., id → maps to ID via languageToIso2()) → +20

Timezone (20%): Reads the timezone cookie and maps it via timezoneToCountry():

  • Asia/Jakarta, Asia/Makassar, etc. → IDN
  • Asia/Kuala_LumpurMYS
  • Asia/SingaporeSGP

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

php
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:

php
// In a service provider
$this->app->singleton(AutoDetectService::class);

Key Files

FilePurpose
app/Services/Location/AutoDetectService.phpWeighted country detection using phone, language, timezone
app/Models/Geographic/Country/Country.phpCountries table — stores code, iso2, phone_code