Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Google Places Api Laravel Package

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.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation

    composer require skagarwal/google-places-api
    
  2. Publish Config (Laravel)

    php artisan vendor:publish --provider="SKAgarwal\GoogleApi\ServiceProvider"
    

    Set your API key in config/google.php.

  3. First Use Case

    use SKAgarwal\GoogleApi\PlacesNew\GooglePlaces;
    
    $response = GooglePlaces::make()->autocomplete('New York');
    $places = $response->collect(); // Collection of results
    

Where to Look First

  • Laravel Usage Section: For config setup and basic workflows.
  • API Reference: For method signatures and parameters.
  • Saloon Documentation: For response handling (array(), collect(), json(), etc.).

Implementation Patterns

Core Workflows

  1. Autocomplete Search

    $response = GooglePlaces::make()->autocomplete('coffee shop');
    $predictions = $response->collect()->pluck('description');
    
  2. Nearby Search (New API)

    $response = GooglePlaces::make()->nearbySearch(40.748817, -73.985428, 500.0);
    $places = $response->collect()->map(fn ($place) => $place['name']);
    
  3. Place Details

    $response = GooglePlaces::make()->placeDetails('ChIJD7fiBh9u5kcRYJxi53WGga0');
    $details = $response->array()['result'];
    
  4. Text Search

    $response = GooglePlaces::make()->textSearch('pizza', ['fields' => ['name', 'rating']]);
    $results = $response->collect()->pluck('name', 'rating');
    

Integration Tips

  • 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);
    });
    

Laravel-Specific Patterns

  • 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'));
    

Gotchas and Tips

Pitfalls

  1. API Key Leaks

    • Never hardcode API keys in source files. Use Laravel’s .env and config/google.php.
    • Fix: Validate the config file is not committed to version control.
  2. Rate Limits

    • Google Places API has usage limits. Monitor your quota in the Google Cloud Console.
    • Fix: Implement exponential backoff for retries:
      $response = GooglePlaces::make()->retry(3, 100)->nearbySearch(0, 0, 500.0);
      
  3. Deprecated API (v2.2)

    • Avoid using SKAgarwal\GoogleApi\Places\GooglePlaces (original API). Migrate to PlacesNew for future compatibility.
    • Fix: Update imports and method calls to use the new API.
  4. SSL Verification

    • Disabling SSL (verifySSL: false) is insecure. Use only in development.
    • Fix: Configure a proper SSL setup or use a local proxy.
  5. Field Selection Errors

    • Invalid fields parameters (e.g., typos) return empty responses. Validate against Google’s field list.
    • Fix: Use ['*'] for testing, then narrow down fields.

Debugging

  • 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

    • 400 Bad Request: Invalid parameters or API key.
    • 403 Forbidden: API key not enabled for Places API or quota exceeded.
    • 500 Server Error: Temporary Google API issue. Retry with backoff.

Extension Points

  1. 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);
    
  2. 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'],
            ]);
        }
    }
    
  3. Middleware Add custom middleware to the Saloon client:

    GooglePlaces::make()->withMiddleware(new CustomMiddleware());
    

Configuration Quirks

  • 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);
    

Performance Tips

  • 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');
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky