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

Algoliasearch Client Php Laravel Package

algolia/algoliasearch-client-php

Official Algolia Search API client for PHP 8+. A thin, low-level HTTP client to index and search data, manage indices, and call Algolia’s APIs directly. Install via Composer and start saving objects, searching, and handling tasks in minutes.

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Setup
1. **Installation**:
   ```bash
   composer require algolia/algoliasearch-client-php "^4.0"

Ensure your project uses PHP 8.0+.

  1. First Use Case: Initialize the client with your Algolia credentials:

    use Algolia\AlgoliaSearch\SearchClient;
    
    $client = SearchClient::create(env('ALGOLIA_APP_ID'), env('ALGOLIA_API_KEY'));
    
  2. First Indexing Operation: Save a record to an index:

    $response = $client->saveObject('products', [
        'objectID' => '123',
        'name' => 'Laptop',
        'price' => 999.99
    ]);
    
  3. First Search Query:

    $results = $client->search('products', 'laptop');
    dd($results['hits']);
    

Where to Look First


Implementation Patterns

Core Workflows

1. Indexing Data

  • Bulk Operations: Use saveObjects() for batch inserts:
    $client->saveObjects('products', [
        ['objectID' => '1', 'name' => 'Product 1'],
        ['objectID' => '2', 'name' => 'Product 2'],
    ]);
    
  • Partial Updates:
    $client->partialUpdateObject('products', '1', ['price' => 899.99]);
    
  • Async Task Handling:
    $response = $client->saveObject('products', ['objectID' => '3', 'name' => 'Product 3']);
    $client->waitForTask('products', $response['taskID']); // Poll until indexed
    

2. Searching

  • Basic Search:
    $results = $client->search('products', 'laptop', [
        'hitsPerPage' => 10,
        'attributesToHighlight' => ['name']
    ]);
    
  • Multi-Index Queries:
    $results = $client->multipleQueries([
        ['indexName' => 'products', 'query' => 'laptop'],
        ['indexName' => 'categories', 'query' => 'electronics'],
    ]);
    
  • Faceting:
    $results = $client->search('products', 'laptop', [
        'facets' => ['category', 'brand'],
        'facetsStatistics' => ['price'],
    ]);
    

3. Advanced Features

  • Synonyms:
    $client->addSynonyms('products', ['laptop:notebook']);
    
  • Rules:
    $client->addRules('products', [
        ['anchor' => 'best', 'indices' => ['products'], 'objectIDs' => ['123']]
    ]);
    
  • Analytics:
    $client->addAnalyticsEvents('products', [
        ['eventType' => 'click', 'objectID' => '123', 'timestamp' => time()]
    ]);
    

4. Ingestion (Algolia Ingestion API)

  • Source Management:
    $client->createSource('products_source', ['type' => 'mysql']);
    
  • Pipeline Execution:
    $client->runSource('products_source');
    

Integration Tips

  • Laravel: Use scout-extended for Eloquent model integration.
  • Symfony: Use search-bundle for Doctrine ORM support.
  • Caching Responses: Cache search results in Laravel/Symfony using Cache facade or Symfony’s Cache component.
  • Error Handling:
    try {
        $client->search('products', 'invalid-query');
    } catch (\Algolia\AlgoliaSearch\Exceptions\AlgoliaException $e) {
        Log::error($e->getMessage());
    }
    

Gotchas and Tips

Pitfalls

  1. API Key Permissions:

    • Use search key for read-only operations (safer).
    • Use admin key for indexing/deleting (avoid exposing in client-side code).
    • Gotcha: A 403 error often means insufficient API key permissions.
  2. Rate Limits:

    • Algolia enforces rate limits. Handle 429 responses gracefully:
      if ($response->getStatusCode() === 429) {
          sleep($response->getHeader('Retry-After'));
      }
      
  3. Async Task Timeouts:

    • waitForTask() polls by default. For long-running tasks, implement exponential backoff:
      $client->waitForTask('products', $taskID, ['timeout' => 30000, 'maxRetries' => 10]);
      
  4. ObjectID Uniqueness:

    • Algolia requires objectID to be unique per index. Reusing IDs without deletion causes conflicts.
  5. Deprecated Methods:

    • Avoid exhaustiveFacetsCount (deprecated in v4). Use facetsStatistics instead.

Debugging Tips

  • Enable Debug Mode:
    $client = SearchClient::create('APP_ID', 'API_KEY', [
        'debug' => true, // Logs HTTP requests/responses
    ]);
    
  • Check Response Headers: Use getHeaders() to inspect Algolia-specific headers (e.g., X-Algolia-Request-ID for troubleshooting).
  • Validate JSON: Ensure payloads are valid JSON (Algolia rejects malformed data silently).

Configuration Quirks

  1. Proxy Settings: Configure proxy for self-hosted or restricted environments:

    $client = SearchClient::create('APP_ID', 'API_KEY', [
        'proxy' => ['http' => 'http://proxy.example.com:8080'],
    ]);
    
  2. Timeouts: Adjust timeout for slow networks:

    $client = SearchClient::create('APP_ID', 'API_KEY', [
        'timeout' => 30, // seconds
    ]);
    
  3. SSL Verification: Disable SSL verification only for testing (not production):

    $client = SearchClient::create('APP_ID', 'API_KEY', [
        'verifySsl' => false,
    ]);
    

Extension Points

  1. Custom HTTP Client: Replace the default Guzzle client for advanced use cases:

    $client = SearchClient::create('APP_ID', 'API_KEY', [
        'httpClient' => new CustomHttpClient(),
    ]);
    
  2. Middleware: Add request/response middleware for logging, auth, or transformation:

    $client->getHttpClient()->getEmitter()->addSubscriber(new CustomMiddleware());
    
  3. Model Transformers: Use Laravel’s toSearchableArray() or Symfony’s Normalizer to transform Eloquent/Doctrine entities before indexing:

    // Laravel Example
    public function toSearchableArray()
    {
        return [
            'objectID' => $this->id,
            'title' => $this->name,
            'price' => $this->price,
        ];
    }
    
  4. Webhook Integration: Use Algolia’s webhooks to trigger actions on index updates:

    $client->setWebhook('products', 'https://your-app.com/algolia-webhook');
    

Performance Tips

  • Batch Indexing: Use chunkedBatch() for large datasets to avoid timeouts:
    $client->chunkedBatch('products', $objects, 1000); // 1000 objects per batch
    
  • Search Parameters: Limit hitsPerPage and attributesToRetrieve to reduce payload size.
  • Index Settings: Pre-configure indexes (e.g., searchableAttributes, customRanking) to optimize relevance.

Community Resources

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
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
twbs/bootstrap4
php-http/client-implementation
phpcr/phpcr-implementation
cucumber/gherkin-monorepo
haydenpierce/class-finder
psr/simple-cache-implementation
uri-template/tests