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

Typesense Php Laravel Package

typesense/typesense-php

Official PHP client for the Typesense search API. Install via Composer with an HTTPlug-compatible HTTP client, then manage collections, documents, and searches using the Typesense server API. Includes examples and safe filter string escaping.

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Setup
1. **Installation**:
   ```bash
   composer require php-http/curl-client typesense/typesense-php

(Use guzzlehttp/guzzle or another HTTPlug-compatible client if preferred.)

  1. Initialize Client:

    use Typesense\Client;
    use Typesense\Connection;
    use Typesense\TypesenseException;
    
    $client = Client::fromOptions([
        'nodes' => [
            new Connection('http://localhost:8108'),
        ],
        'api_key' => 'your-api-key',
        'connection_timeout_seconds' => 2,
    ]);
    
  2. First Use Case: Search

    try {
        $searchResults = $client->collections('products')
            ->documents()
            ->search('query=laptop', 10);
        dd($searchResults->get('hits'));
    } catch (TypesenseException $e) {
        // Handle errors (e.g., network issues, invalid API key)
        dd($e->getMessage());
    }
    

Key Entry Points

  • Collections: $client->collections('collection_name')
  • Documents: $client->collections('collection_name')->documents()
  • Schemas: $client->collections('collection_name')->schema()
  • Aliases: $client->aliases()

Docs: Typesense API Reference | Examples


Implementation Patterns

1. Search Workflows

Basic Search

$searchResults = $client->collections('products')
    ->documents()
    ->search('query=wireless headphones&query_by=title,description', 20);

Filtered Search

$searchResults = $client->collections('products')
    ->documents()
    ->search('query=headphones&filter_by=price:[100 TO *]');

Paginated Search

$searchResults = $client->collections('products')
    ->documents()
    ->search('query=headphones&per_page=10&page=2');

Natural Language Search (NLS)

$searchResults = $client->collections('products')
    ->documents()
    ->search('query=best headphones&nls=true');

2. CRUD Operations

Create Document

$document = [
    'title' => 'Wireless Headphones',
    'price' => 199.99,
    'description' => 'Noise-cancelling wireless headphones',
];
$client->collections('products')->documents()->upsert($document);

Batch Upsert

$documents = [
    ['title' => 'Product 1', 'price' => 100],
    ['title' => 'Product 2', 'price' => 200],
];
$client->collections('products')->documents()->upsert($documents);

Delete Document

$client->collections('products')->documents()->delete('document_id');

3. Schema Management

Create Schema

$schema = [
    'name' => 'products',
    'fields' => [
        ['name' => 'title', 'type' => 'string'],
        ['name' => 'price', 'type' => 'int32'],
    ],
];
$client->collections()->create($schema);

Update Schema

$updatedSchema = [
    'fields' => [
        ['name' => 'title', 'type' => 'string', 'optional' => true],
    ],
];
$client->collections('products')->schema()->update($updatedSchema);

4. Advanced Features

Multi-Search

$searches = [
    ['collection' => 'products', 'query' => 'headphones'],
    ['collection' => 'electronics', 'query' => 'laptops'],
];
$results = $client->multiSearch()->search($searches);

Analytics Events

$client->collections('products')->analytics()->events()->create([
    'event_name' => 'product_view',
    'document_id' => '123',
    'properties' => ['user_id' => '456'],
]);

Custom Logger

use Psr\Log\LoggerInterface;

$logger = new CustomLogger();
$client = Client::fromOptions([
    'nodes' => [new Connection('http://localhost:8108')],
    'api_key' => 'your-api-key',
    'logger' => $logger, // Inject custom logger
]);

5. Integration with Laravel

Service Provider

// app/Providers/TypesenseServiceProvider.php
use Illuminate\Support\ServiceProvider;
use Typesense\Client;
use Typesense\Connection;

class TypesenseServiceProvider extends ServiceProvider
{
    public function register()
    {
        $this->app->singleton('typesense', function () {
            return Client::fromOptions([
                'nodes' => [new Connection(config('typesense.nodes.0'))],
                'api_key' => config('typesense.api_key'),
            ]);
        });
    }
}

Config File (config/typesense.php)

return [
    'nodes' => [
        'http://localhost:8108',
    ],
    'api_key' => env('TYPESENSE_API_KEY'),
    'connection_timeout_seconds' => 2,
];

Usage in Controllers

use Illuminate\Support\Facades\Typesense;

public function search()
{
    $results = Typesense::collections('products')
        ->documents()
        ->search('query=headphones');
    return response()->json($results->get('hits'));
}

Gotchas and Tips

1. FilterBy Escaping

  • Pitfall: Unescaped strings in filter_by queries can break searches (e.g., &&, ||, %).
  • Solution: Use FilterBy::escapeString():
    use Typesense\FilterBy;
    
    $filterValue = "The 17\" O'Conner && O`Series";
    $escaped = FilterBy::escapeString($filterValue);
    $search = $client->collections('products')
        ->documents()
        ->search("query=*&filter_by=tags:={$escaped}");
    

2. Error Handling

  • Common Exceptions:
    • TypesenseException: Network issues, invalid API keys, or server errors.
    • JsonException: Malformed JSON responses (handled in v6.1.0+).
  • Retry Logic: The client retries on 500/408 errors by default. Disable with:
    $client = Client::fromOptions([
        'nodes' => [new Connection('http://localhost:8108')],
        'api_key' => 'your-api-key',
        'retry_on_status_codes' => [], // Disable retries
    ]);
    

3. Configuration Quirks

  • HTTPlug Compatibility: Ensure your HTTP client (e.g., curl-client, guzzle) is HTTPlug-compatible.
  • Node Selection: For distributed setups, the client shuffles nodes to avoid thundering herds (since v5.2.0).
  • Breaking Changes:
    • v5.0.0+: Resource names (collections, aliases) are auto-URL-encoded. Remove manual encoding in your app.
    • v6.0.0+: Supports Typesense v30 features (e.g., /operations/schema_changes).

4. Performance Tips

  • Batch Operations: Use upsert() with arrays for bulk inserts:
    $client->collections('products')->documents()->upsert([$doc1, $doc2, $doc3]);
    
  • Pagination: Limit per_page to reduce payload size:
    $searchResults = $client->collections('products')
        ->documents()
        ->search('query=*&per_page=50');
    
  • Caching: Cache search results in Laravel using Cache::remember():
    $results = Cache::remember('typesense_headphones', 3600, function () {
        return $client->collections('products')
            ->documents()
            ->search('query=headphones');
    });
    

5. Debugging

  • Enable Logging:
    $client = Client::fromOptions([
        'nodes' => [new Connection('http://localhost:8108')],
        'api_key' => 'your-api-key',
        'logger' => new \Monolog\Logger('typesense', [
            new \Monolog\Handler\StreamHandler(__DIR__.'/typesense.log', \Monolog\Logger::DEBUG),
        ]),
    ]);
    
  • Validate API Responses: Use getRawResponse() to inspect raw HTTP responses:
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.
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament