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

Meilisearch Php Laravel Package

meilisearch/meilisearch-php

Official PHP client for Meilisearch, the open‑source search engine. Connect to Meilisearch or Meilisearch Cloud to index documents, configure indexes, and run fast, typo‑tolerant searches. Supports customizable HTTP clients and common PHP tooling.

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Setup in Laravel
1. **Install the package** with Guzzle (recommended for Laravel):
   ```bash
   composer require meilisearch/meilisearch-php guzzlehttp/guzzle http-interop/http-factory-guzzle
  1. Configure the client in a service provider or config file:
    // config/meilisearch.php
    return [
        'host' => env('MEILISEARCH_HOST', 'http://127.0.0.1:7700'),
        'api_key' => env('MEILISEARCH_MASTER_KEY', 'masterKey'),
    ];
    
  2. Create a helper class (e.g., app/Services/MeilisearchService.php):
    namespace App\Services;
    
    use Meilisearch\Client;
    
    class MeilisearchService
    {
        protected $client;
    
        public function __construct()
        {
            $this->client = new Client(config('meilisearch.host'), config('meilisearch.api_key'));
        }
    
        public function index(string $name)
        {
            return $this->client->index($name);
        }
    }
    
  3. Bind the service in AppServiceProvider:
    public function register()
    {
        $this->app->singleton(MeilisearchService::class, function ($app) {
            return new MeilisearchService();
        });
    }
    
  4. First use case: Index documents in a controller:
    use App\Services\MeilisearchService;
    
    public function indexMovies(MeilisearchService $meilisearch)
    {
        $index = $meilisearch->index('movies');
        $movies = [
            ['id' => 1, 'title' => 'Inception', 'genres' => ['Sci-Fi', 'Action']],
        ];
        $index->addDocuments($movies);
        return response()->json(['status' => 'success']);
    }
    

Implementation Patterns

Common Workflows

1. Search with Typo Tolerance

$hits = $meilisearch->index('products')->search('smartphon')->getHits();
  • Laravel Integration: Wrap in a service method:
    public function searchProducts(string $query)
    {
        return $this->index('products')->search($query)->getHits();
    }
    

2. Filtered Search with Facets

$results = $meilisearch->index('products')->search('laptop', [
    'filter' => ['price > 500 AND stock > 0'],
    'facets' => ['category', 'brand'],
]);
  • Laravel: Use in a controller with request validation:
    public function search(Request $request)
    {
        $query = $request->input('q');
        $filters = $request->input('filters', []);
    
        return $this->searchProducts($query, $filters);
    }
    

3. Bulk Document Updates

$index = $meilisearch->index('users');
$index->updateDocuments([
    ['id' => 1, 'name' => 'Updated Name'],
    ['id' => 2, 'email' => 'new@example.com'],
]);
  • Laravel: Chain with Eloquent models:
    public function syncUsers()
    {
        $users = User::all()->map(fn ($user) => [
            'id' => $user->id,
            'name' => $user->name,
            'email' => $user->email,
        ]);
        $this->index('users')->addDocuments($users);
    }
    

4. Async Task Handling

$task = $index->addDocuments($documents);
$status = $task->waitUntilCompleted(); // Blocks until done
  • Laravel: Use queues for long-running tasks:
    public function indexDocuments()
    {
        IndexDocumentsJob::dispatch($documents);
    }
    
    // IndexDocumentsJob.php
    public function handle()
    {
        $task = $this->meilisearch->index('products')->addDocuments($this->documents);
        $task->waitUntilCompleted();
    }
    

5. Dynamic Index Settings

$index->updateSettings([
    'searchableAttributes' => ['title', 'description'],
    'filterableAttributes' => ['category', 'price'],
]);
  • Laravel: Store settings in config/database:
    public function configureIndex()
    {
        $settings = config('meilisearch.index_settings.products');
        $this->index('products')->updateSettings($settings);
    }
    

Integration Tips

  1. Use Laravel Events:

    • Trigger Meilisearch updates on model events:
      // UserObserver.php
      public function saved(User $user)
      {
          event(new UserUpdated($user));
      }
      
      // Listen to UserUpdated
      public function handle(UserUpdated $event)
      {
          $this->meilisearch->index('users')->updateDocuments([$event->user->toArray()]);
      }
      
  2. Cache Search Results:

    • Cache hits for 5 minutes:
      public function search(string $query)
      {
          return Cache::remember("meilisearch:{$query}", now()->addMinutes(5), function () use ($query) {
              return $this->meilisearch->index('products')->search($query)->getHits();
          });
      }
      
  3. Rate Limiting:

    • Use Laravel’s throttle middleware for API calls:
      Route::middleware(['throttle:10,1'])->group(function () {
          Route::get('/search', [SearchController::class, 'index']);
      });
      
  4. Environment-Specific Configs:

    • Use .env for different Meilisearch instances:
      MEILISEARCH_HOST=production ? 'https://meilisearch.prod.com' : 'http://localhost:7700'
      MEILISEARCH_MASTER_KEY=production ? env('PROD_MEILI_KEY') : 'masterKey'
      
  5. Testing:

    • Mock the client in tests:
      $mock = Mockery::mock(MeilisearchService::class);
      $mock->shouldReceive('index')->andReturnSelf();
      $mock->shouldReceive('search')->andReturn(new SearchResult([], 0, 0, 0, 'test'));
      $this->app->instance(MeilisearchService::class, $mock);
      

Gotchas and Tips

Pitfalls

  1. Async Operations:

    • addDocuments() and updateDocuments() return a Task object. Always check its status or wait for completion:
      $task = $index->addDocuments($docs);
      if (!$task->isCompleted()) {
          $task->waitUntilCompleted(); // Blocks
          // OR use callbacks:
          $task->onCompleted(function () { /* ... */ });
      }
      
  2. Index Creation:

    • Indices are created implicitly when adding documents, but explicit creation gives you control over settings:
      $index = $client->index('products', [
          'primaryKey' => 'id',
          'searchableAttributes' => ['title', 'description'],
      ]);
      
  3. Filterable Attributes:

    • Forgetting to update filterableAttributes will cause silent failures. Always verify:
      $settings = $index->getSettings();
      if (!in_array('category', $settings['filterableAttributes'])) {
          $index->updateFilterableAttributes(array_merge($settings['filterableAttributes'], ['category']));
      }
      
  4. Typo Tolerance:

    • Meilisearch is typo-tolerant by default, but this can be disabled:
      $index->updateTypoTolerance(['enabled' => false]);
      
  5. Pagination:

    • Use offset and limit for pagination, but avoid large offsets (e.g., offset=10000):
      $hits = $index->search('query', ['offset' => 0, 'limit' => 20])->getHits();
      
  6. Special Characters in Queries:

    • Escape special characters in filters:
      $filter = str_replace(['\\', '"'], ['\\\\', '\\"'], $userInput);
      $index->search('query', ['filter' => $filter]);
      

Debugging Tips

  1. Enable Debugging:

    • Log raw API responses for debugging:
      $client = new Client($host, $key, new GuzzleHttpClient([
          'debug' => fopen('meilisearch_debug.log', 'w'),
      ]));
      
  2. Task Status:

    • Check task status if operations seem stuck:
      $task = $index->addDocuments($docs);
      $status = $task->getStatus
      
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.
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
leek/filament-subtenant-scope