skagarwal/google-places-api
PHP wrapper for Google Places API Web Service with Laravel support. Includes Places API and Places API (New) endpoints like autocomplete/search, built on Saloon in v3. Composer install, fluent client setup, configurable SSL and error handling.
Installation
composer require skagarwal/google-places-api
Publish Config (Laravel)
php artisan vendor:publish --provider="SKAgarwal\GoogleApi\ServiceProvider"
Set your API key in config/google.php.
First Use Case
use SKAgarwal\GoogleApi\PlacesNew\GooglePlaces;
$response = GooglePlaces::make()->autocomplete('New York');
$places = $response->collect(); // Collection of results
array(), collect(), json(), etc.).Autocomplete Search
$response = GooglePlaces::make()->autocomplete('coffee shop');
$predictions = $response->collect()->pluck('description');
Nearby Search (New API)
$response = GooglePlaces::make()->nearbySearch(40.748817, -73.985428, 500.0);
$places = $response->collect()->map(fn ($place) => $place['name']);
Place Details
$response = GooglePlaces::make()->placeDetails('ChIJD7fiBh9u5kcRYJxi53WGga0');
$details = $response->array()['result'];
Text Search
$response = GooglePlaces::make()->textSearch('pizza', ['fields' => ['name', 'rating']]);
$results = $response->collect()->pluck('name', 'rating');
Chaining Methods
$response = GooglePlaces::make()
->headers()->add('X-Custom-Header', 'value')
->autocomplete('restaurant');
Field Selection
Use fields parameter to optimize API calls:
$response = GooglePlaces::make()->nearbySearch(37.7749, -122.4194, 1000.0, ['fields' => ['name', 'geometry.location']]);
Error Handling
try {
$response = GooglePlaces::make()->throw()->nearbySearch(0, 0, 500.0);
} catch (\Saloon\Http\Exceptions\SaloonException $e) {
Log::error('Google Places API Error: ' . $e->getMessage());
}
Caching Responses Cache frequent queries (e.g., autocomplete) using Laravel’s cache:
$cacheKey = 'places_autocomplete_' . md5($input);
$response = Cache::remember($cacheKey, now()->addMinutes(10), function () use ($input) {
return GooglePlaces::make()->autocomplete($input);
});
Service Container Binding
Bind the client in AppServiceProvider for dependency injection:
$this->app->bind(GooglePlaces::class, function ($app) {
return GooglePlaces::make();
});
API Key Management
Store the key in .env and access via config('google.api_key'):
GooglePlaces::make()->setKey(config('google.api_key'));
API Key Leaks
.env and config/google.php.Rate Limits
$response = GooglePlaces::make()->retry(3, 100)->nearbySearch(0, 0, 500.0);
Deprecated API (v2.2)
SKAgarwal\GoogleApi\Places\GooglePlaces (original API). Migrate to PlacesNew for future compatibility.SSL Verification
verifySSL: false) is insecure. Use only in development.Field Selection Errors
fields parameters (e.g., typos) return empty responses. Validate against Google’s field list.['*'] for testing, then narrow down fields.Response Inspection Log raw responses to debug:
$response = GooglePlaces::make()->autocomplete('test');
Log::debug('Google Places Response:', ['status' => $response->status(), 'body' => $response->body()]);
Saloon Logging Enable Saloon’s debug mode:
GooglePlaces::make()->debug();
Common HTTP Errors
Custom Requests
Extend the client for unsupported endpoints using Saloon’s extend method:
GooglePlaces::extend('customSearch', function () {
return new SaloonHttp($this->config);
})->addRequest('customSearch', \SKAgarwal\GoogleApi\PlacesNew\Requests\CustomSearch::class);
Response Transformers
Modify responses globally by extending the GooglePlaces class:
class CustomGooglePlaces extends GooglePlaces {
public function transformResponse($response) {
$data = parent::transformResponse($response);
return collect($data)->map(fn ($item) => [
'id' => $item['place_id'],
'name' => $item['name'],
]);
}
}
Middleware Add custom middleware to the Saloon client:
GooglePlaces::make()->withMiddleware(new CustomMiddleware());
Headers in Config
Set default headers in config/google.php:
'headers' => [
'Accept-Language' => 'en-US',
],
Environment-Specific Keys
Use Laravel’s env() helper to switch keys per environment:
GooglePlaces::make()->setKey(env('GOOGLE_PLACES_API_KEY_' . config('app.env')));
Throwing Exceptions Default behavior is silent failure. Enable exceptions per request:
$response = GooglePlaces::make()->throw()->nearbySearch(0, 0, 500.0);
Batch Requests For multiple searches, batch requests to reduce latency:
$locations = ['40.748817,-73.985428', '34.052235,-118.243683'];
$results = collect($locations)->map(fn ($loc) => GooglePlaces::make()->nearbySearch($loc, 500.0)->collect());
Field Pruning Request only necessary fields to reduce payload size:
$response = GooglePlaces::make()->nearbySearch(0, 0, 500.0, ['fields' => ['name', 'geometry.location']]);
Async Processing Use Laravel Queues for non-critical searches:
SearchPlacesJob::dispatch('restaurant')->onQueue('places');
How can I help you explore Laravel packages today?