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.
## Getting Started
### Minimal Setup
1. **Installation**:
```bash
composer require algolia/algoliasearch-client-php "^4.0"
Ensure your project uses PHP 8.0+.
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'));
First Indexing Operation: Save a record to an index:
$response = $client->saveObject('products', [
'objectID' => '123',
'name' => 'Laptop',
'price' => 999.99
]);
First Search Query:
$results = $client->search('products', 'laptop');
dd($results['hits']);
SearchClient class for core methods (e.g., search(), saveObject(), deleteObject()).saveObjects() for batch inserts:
$client->saveObjects('products', [
['objectID' => '1', 'name' => 'Product 1'],
['objectID' => '2', 'name' => 'Product 2'],
]);
$client->partialUpdateObject('products', '1', ['price' => 899.99]);
$response = $client->saveObject('products', ['objectID' => '3', 'name' => 'Product 3']);
$client->waitForTask('products', $response['taskID']); // Poll until indexed
$results = $client->search('products', 'laptop', [
'hitsPerPage' => 10,
'attributesToHighlight' => ['name']
]);
$results = $client->multipleQueries([
['indexName' => 'products', 'query' => 'laptop'],
['indexName' => 'categories', 'query' => 'electronics'],
]);
$results = $client->search('products', 'laptop', [
'facets' => ['category', 'brand'],
'facetsStatistics' => ['price'],
]);
$client->addSynonyms('products', ['laptop:notebook']);
$client->addRules('products', [
['anchor' => 'best', 'indices' => ['products'], 'objectIDs' => ['123']]
]);
$client->addAnalyticsEvents('products', [
['eventType' => 'click', 'objectID' => '123', 'timestamp' => time()]
]);
$client->createSource('products_source', ['type' => 'mysql']);
$client->runSource('products_source');
scout-extended for Eloquent model integration.search-bundle for Doctrine ORM support.Cache facade or Symfony’s Cache component.try {
$client->search('products', 'invalid-query');
} catch (\Algolia\AlgoliaSearch\Exceptions\AlgoliaException $e) {
Log::error($e->getMessage());
}
API Key Permissions:
search key for read-only operations (safer).admin key for indexing/deleting (avoid exposing in client-side code).403 error often means insufficient API key permissions.Rate Limits:
429 responses gracefully:
if ($response->getStatusCode() === 429) {
sleep($response->getHeader('Retry-After'));
}
Async Task Timeouts:
waitForTask() polls by default. For long-running tasks, implement exponential backoff:
$client->waitForTask('products', $taskID, ['timeout' => 30000, 'maxRetries' => 10]);
ObjectID Uniqueness:
objectID to be unique per index. Reusing IDs without deletion causes conflicts.Deprecated Methods:
exhaustiveFacetsCount (deprecated in v4). Use facetsStatistics instead.$client = SearchClient::create('APP_ID', 'API_KEY', [
'debug' => true, // Logs HTTP requests/responses
]);
getHeaders() to inspect Algolia-specific headers (e.g., X-Algolia-Request-ID for troubleshooting).Proxy Settings: Configure proxy for self-hosted or restricted environments:
$client = SearchClient::create('APP_ID', 'API_KEY', [
'proxy' => ['http' => 'http://proxy.example.com:8080'],
]);
Timeouts: Adjust timeout for slow networks:
$client = SearchClient::create('APP_ID', 'API_KEY', [
'timeout' => 30, // seconds
]);
SSL Verification: Disable SSL verification only for testing (not production):
$client = SearchClient::create('APP_ID', 'API_KEY', [
'verifySsl' => false,
]);
Custom HTTP Client: Replace the default Guzzle client for advanced use cases:
$client = SearchClient::create('APP_ID', 'API_KEY', [
'httpClient' => new CustomHttpClient(),
]);
Middleware: Add request/response middleware for logging, auth, or transformation:
$client->getHttpClient()->getEmitter()->addSubscriber(new CustomMiddleware());
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,
];
}
Webhook Integration: Use Algolia’s webhooks to trigger actions on index updates:
$client->setWebhook('products', 'https://your-app.com/algolia-webhook');
chunkedBatch() for large datasets to avoid timeouts:
$client->chunkedBatch('products', $objects, 1000); // 1000 objects per batch
hitsPerPage and attributesToRetrieve to reduce payload size.searchableAttributes, customRanking) to optimize relevance.How can I help you explore Laravel packages today?