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

Googlesearch Laravel Package

spatie/googlesearch

Fetch search results from a paid Google Custom Search Engine in PHP/Laravel. Includes service provider, facade, and configurable API key/CSE ID setup to return results as an array for easy integration into your app.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require spatie/googlesearch
    

    Add to config/services.php (if not present):

    'google-search' => [
        'engine_id' => env('GOOGLE_SEARCH_ENGINE_ID'),
        'api_key'   => env('GOOGLE_API_KEY'),
    ],
    
  2. Environment Variables:

    GOOGLE_SEARCH_ENGINE_ID=your_custom_search_engine_id
    GOOGLE_API_KEY=your_api_key
    
  3. First Query:

    use Spatie\GoogleSearch\GoogleSearch;
    
    $results = GoogleSearch::search('laravel best practices');
    // Returns array of results with metadata (title, link, snippet, etc.)
    

First Use Case: Scraping Search Results

// Fetch top 5 results for a query
$results = GoogleSearch::search('laravel 10 features', 5);

// Access a specific result
$firstResult = $results[0];
echo $firstResult['title']; // Outputs the title of the first result

Implementation Patterns

Querying with Filters

// Search with start index (pagination)
$results = GoogleSearch::search('laravel testing', 10, 1); // 10 results, starting at index 1

// Search with custom parameters (e.g., date range)
$results = GoogleSearch::search('laravel news', 5, 1, [
    'cr' => 'countryUS', // Restrict to US
    'tbs' => 'qdr:m',     // Last month
]);

Integration with Laravel Services

Service Provider Binding:

// app/Providers/AppServiceProvider.php
public function register()
{
    $this->app->singleton(GoogleSearch::class, function ($app) {
        return new GoogleSearch(
            config('services.google-search.engine_id'),
            config('services.google-search.api_key')
        );
    });
}

Usage in Controllers:

public function search(Request $request)
{
    $query = $request->input('q', 'default query');
    $results = app(GoogleSearch::class)->search($query);

    return view('search.results', compact('results'));
}

Caching Results

// Cache results for 1 hour
$results = Cache::remember("google_{$query}", 3600, function () use ($query) {
    return GoogleSearch::search($query);
});

Batch Processing

// Process multiple queries in a loop
$queries = ['laravel', 'php', 'symfony'];
foreach ($queries as $query) {
    $results = GoogleSearch::search($query);
    // Store or process results
}

Gotchas and Tips

API Key and Engine ID

  • Pitfall: Forgetting to set up a Google Custom Search Engine (CSE) before using the package.

  • Pitfall: Hardcoding API keys or engine IDs in code.

    • Fix: Always use .env and Laravel’s config/services.php.

Rate Limiting and Quotas

  • Pitfall: Hitting Google’s API quota limits (e.g., 100 free queries/day).
    • Fix:
      • Cache results aggressively (e.g., 24-hour cache).
      • Use try-catch to handle Google_Service_Exception for quota errors.
      try {
          $results = GoogleSearch::search('query');
      } catch (\Google_Service_Exception $e) {
          Log::error('Google Search API quota exceeded: ' . $e->getMessage());
          return back()->with('error', 'Search service unavailable.');
      }
      

Result Parsing

  • Tip: The package returns raw results from Google’s API. Sanitize output before rendering:
    $safeTitle = htmlspecialchars($result['title']);
    
  • Pitfall: Assuming all results have the same structure (e.g., missing snippet or link).
    • Fix: Use isset() or data_get() to safely access nested keys:
      $snippet = data_get($result, 'snippet', 'No snippet available.');
      

Debugging

  • Tip: Enable verbose logging for API responses:
    GoogleSearch::setLogger(function ($message) {
        Log::debug('Google Search API:', ['message' => $message]);
    });
    
  • Pitfall: Silent failures due to invalid API keys or engine IDs.
    • Fix: Check storage/logs/laravel.log for Google_Service_Exception errors.

Extending Functionality

  • Tip: Wrap the package in a custom service for reusable logic:
    // app/Services/GoogleSearchService.php
    class GoogleSearchService
    {
        public function searchWithFallback($query)
        {
            try {
                return GoogleSearch::search($query);
            } catch (\Exception $e) {
                return $this->fallbackToLocalDatabase($query);
            }
        }
    }
    

Deprecation Note

  • Warning: The package is archived (last release in 2016) and may not support newer Laravel versions or PHP features.
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.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport