Geocoder service provider for Laravel
If you still use Laravel 4, please check out the
0.4.xbranch here.
Version 13.0.0 is a backwards-compatibility-breaking update. Please review the Upgrading section, especially the new default HTTP adapter, before installing.
Versioning change: starting with
13.0.0, this package's major version tracks the highest supported Laravel major version, instead of the upstream Geocoder PHP version. So13.xsupports Laravel 11/12/13, the next major will be14.xwhen Laravel 14 ships, and so on. The previous tag was5.0.0; the jump to13.0.0reflects the new versioning scheme, not 9 intermediate releases.
This package allows you to use Geocoder in Laravel.
composer require toin0u/geocoder-laravelproviders array key in config/app.php and register
the Geocoder Service Provider:// 'providers' => [
Geocoder\Laravel\Providers\GeocoderService::class,
// ];composer.json file to prevent stale caches when upgrading or updating the package, both in your live and dev environments: "post-update-cmd": [
"@php artisan cache:clear",
],
"post-install-cmd": [
"@php artisan cache:clear",
]Pay special attention to the language and region values if you are using them. For example, the GoogleMaps provider uses TLDs for region values, and the following for language values: https://developers.google.com/maps/faq#languagesupport.
Further, a special note on the GoogleMaps provider: if you are using an API key, you must also use set HTTPS to true. (Best is to leave it true always, unless there is a special requirement not to.)
See the Geocoder documentation for a list of available adapters and providers.
To implement the dedicated cache store, add another redis store entry in
config/database.php, something like the following:
"redis" => [
// ...
"geocode-cache" => [ // choose an appropriate name
'host' => env('REDIS_HOST', '192.168.10.10'),
'password' => env('REDIS_PASSWORD', null),
'port' => env('REDIS_PORT', 6379),
'database' => 1, // be sure this number differs from your other redis databases
],
]You will also need to add an entry in config/cache.php to point to this redis
database:
"stores" => [
// ...
"geocode" => [
'driver' => 'redis',
'connection' => 'geocode-cache',
],
],Finally, configure Geocoder for Laravel to use this store. Edit
config/geocoder.php:
"cache" => [
"store" => "geocode",
// ...
],You can disable caching on a query-by-query basis as needed, like so:
$results = app("geocoder")
->doNotCache()
->geocode('Los Angeles, CA')
->get();cache.serializable_classes — ImportantLaravel 13 introduced
cache.serializable_classesas a security hardening measure, defaulting tofalseto block deserialization of arbitrary PHP objects from the cache. This package storesCollections ofAddressobjects in the cache, which would silently break caching under the new default.
To keep caching working out of the box without forcing you to maintain an
allow-list as new providers are installed, this package scans the installed
Geocoder vendor directories at boot and merges every model class it finds into
your application's cache.serializable_classes allow-list. Whatever
providers you have installed under vendor/geocoder-php/* are covered
automatically — there's no curated list to go stale.
** Security implication:** the package narrowly relaxes Laravel 13's hardening
for the geocoder model classes installed in your vendor/ directory. Other
PHP objects you store in the cache remain blocked unless you explicitly allow
them. The blast radius is bounded to classes you've already deliberately
installed via composer.
Opting out. Set auto_register_serializable_classes to false in your
config/geocoder.php:
'cache' => [
// ...
'auto_register_serializable_classes' => false,
],When opted out, the package will not touch cache.serializable_classes at all.
You then have two reasonable paths:
Manage the allow-list yourself. Add the geocoder model classes to
config/cache.php's serializable_classes directly. Caching keeps working
under your explicit control. Pick this if you want to audit exactly which
PHP objects your application allows to deserialize from cache.
Disable caching for geocoder queries. Call
app('geocoder')->doNotCache() on each query, or set cache.duration to
0 in config/geocoder.php. Pick this if you don't want to maintain the
allow-list and can absorb the per-request API cost.
Doing neither under Laravel 13 could cause __PHP_Incomplete_Class corruption
on cached results.
If you are upgrading and have previously published the geocoder config file, you
need to add the cache-duration variable, otherwise cache will be disabled
(it will default to a 0 cache duration). The default cache duration provided
by the config file is 999999999 seconds, essentially forever.
By default, the configuration specifies a Chain provider, containing the GoogleMaps provider for addresses as well as reverse lookups with lat/long, and the GeoIP provider for IP addresses. The first to return a result will be returned, and subsequent providers will not be executed. The default config file is kept lean with only those two providers.
However, you are free to add or remove providers as needed, both inside the Chain provider, as well as along-side it. The following is the default configuration provided by the package:
…By default we ship Geocoder\Laravel\Http\LaravelHttpClient, a thin PSR-18
client that delegates every request to Laravel's Http facade. This means:
Http::fake() and Http::assertSent() work in your tests with no extra setupYou can pass constructor arguments to the adapter via the array form
[Class => [args]] in config/geocoder.php. Arguments are forwarded directly
to the adapter's constructor — it's on you to match its signature. Named
arguments are supported.
The default LaravelHttpClient accepts timeout, connectTimeout, retry,
and options (Guzzle transport options). These are forwarded to the
underlying Laravel PendingRequest:
'adapter' => [LaravelHttpClient::class => [
'timeout' => 10,
'connectTimeout' => 3,
'retry' => [3, 100], // [times, sleepMilliseconds]
'options' => ['verify' => false], // Guzzle transport options
]],Set 'adapter' to any class that implements Psr\Http\Client\ClientInterface.
To go back to the previous CURL adapter, install php-http/curl-client and
pass your CURL options the same way:
'adapter' => [Http\Client\Curl\Client::class => [
null,
null,
[CURLOPT_PROXY => env('CURL_PROXY'), CURLOPT_PROXYUSERPWD => env('CURL_PROXYUSERPWD')],
]],If you would like to make changes to the default configuration, publish and edit the configuration file:
php artisan vendor:publish --provider="Geocoder\Laravel\Providers\GeocoderService" --tag="config"The service provider initializes the geocoder service, accessible via the
facade Geocoder::... or the application helper app('geocoder')->....
app('geocoder')->geocode('Los Angeles, CA')->get();app('geocoder')->geocode('8.8.8.8')->get();app('geocoder')->reverse(43.882587,-103.454067)->get();Use the locale() method to request localized formatting from providers that
support it (GoogleMaps, Nominatim, etc.). Results are cached separately per
locale, so switching locales doesn't pollute each other's cache entries:
app('geocoder')->locale('it')->geocode('Bologna')->get();
app('geocoder')->locale('fr')->reverse(45.5, -73.5)->get();If you need to build a query with additional options, you can also set the
locale directly on a query and pass it through geocodeQuery() or
reverseQuery():
use Geocoder\Query\GeocodeQuery;
$query = GeocodeQuery::create('Bologna')->withLocale('it');
app('geocoder')->geocodeQuery($query)->get();app('geocoder')->geocode('Los Angeles, CA')->dump('kml');use Geocoder\Laravel\ProviderAndDumperAggregator as Geocoder;
class GeocoderController extends Controller
{
public function getGeocode(Geocoder $geocoder)
{
$geocoder->geocode('Los Angeles, CA')->get()
}
}Anytime you upgrade this package, please remember to clear your cache, to prevent incompatible cached responses when breaking changes are introduced (this should hopefully only be necessary in major versions):
php artisan cache:clearUpdate your composer.json:
"toin0u/geocoder-laravel": "^13.0",Yes, the jump from
5.xto13.xis intentional — see the versioning note at the top of this README. There are no5.xthrough12.xreleases.
Breaking: default HTTP adapter changed. The default 'adapter' in
config/geocoder.php is now Geocoder\Laravel\Http\LaravelHttpClient
instead of Http\Client\Curl\Client. The new adapter is a PSR-18 client
that delegates to Laravel's Http facade, so Http::fake(), retries,
timeouts, and middleware all work transparently.
If you have published the geocoder config previously, your config file
still pins the old curl adapter and will fail at runtime once
php-http/curl-client is no longer installed. Pick one:
config/geocoder.php
and re-publish it, then re-apply your customizations.use Http\Client\Curl\Client; to
use Geocoder\Laravel\Http\LaravelHttpClient; and change
'adapter' => Client::class to 'adapter' => LaravelHttpClient::class.composer require php-http/curl-client. The published config keeps working
unchanged.Other notable changes in 13.x:
php-http/curl-client removed from required dependencies (install it
yourself if you still need it).MaxMindBinary provider support removed (the underlying PHP package was
abandoned). Use geocoder-php/geoip2-provider for MaxMind data instead.Update your composer.json:
"toin0u/geocoder-laravel": "^5.0",Update your composer.json file:
"toin0u/geocoder-laravel": "^4.0",The one change to keep in mind here is that the results returned from
Geocoder for Laravel are now using the Laravel-native Collections class
instead of returning an instance of AddressCollection. This should provide
greater versatility in man
No open issues yet, or sync has not completed.