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

Scout Laravel Package

laravel/scout

Laravel Scout adds driver-based full-text search to Eloquent models, automatically syncing model changes to your search indexes. Supports Algolia, Meilisearch, and Typesense, with configuration and usage documented on laravel.com.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require laravel/scout
    

    For a specific driver (e.g., Algolia, Meilisearch, or Typesense), install its dedicated package:

    composer require algolia/algoliasearch-client-php  # or meilisearch/meilisearch-php, typesense/typesense-php
    
  2. Configuration: Publish the config file:

    php artisan vendor:publish --provider="Laravel\Scout\ScoutServiceProvider"
    

    Update .env with your driver-specific credentials (e.g., ALGOLIA_APP_ID, ALGOLIA_SECRET).

  3. Enable Scout on a Model: Add use Laravel\Scout\Searchable; and implement toSearchableArray():

    use Laravel\Scout\Searchable;
    
    class Post extends Model
    {
        use Searchable;
    
        public function toSearchableArray()
        {
            return [
                'title' => $this->title,
                'body' => $this->body,
            ];
        }
    }
    
  4. First Search:

    $results = Post::search('laravel')->get();
    

Key Commands

  • Index Models:
    php artisan scout:import "App\Models\Post"
    
  • Flush Index:
    php artisan scout:flush "App\Models\Post"
    

Implementation Patterns

Core Workflows

  1. Searching:

    • Basic search:
      $posts = Post::search('query')->get();
      
    • With pagination:
      $posts = Post::search('query')->paginate(10);
      
    • Custom query builder:
      $posts = Post::search('query')->where('title', 'like', '%Laravel%')->get();
      
  2. Filtering:

    • Use where() for driver-specific filters:
      $posts = Post::search('query')->where('category', 'news')->get();
      
    • For complex filters, use callback():
      $posts = Post::search('query')->where(function ($query) {
          $query->where('author', 'John')->where('published', true);
      })->get();
      
  3. Sorting:

    • Driver-specific sorting (e.g., Algolia’s setSettings):
      $posts = Post::search('query')->sortBy('created_at')->get();
      
    • Custom sorting via callback():
      $posts = Post::search('query')->callback(function ($query) {
          return $query->sort(['created_at:desc']);
      })->get();
      
  4. Real-Time Updates:

    • Scout automatically syncs changes (create/update/delete) to the search index. Override shouldBeSearchable() to control this:
      public function shouldBeSearchable()
      {
          return $this->isPublished();
      }
      
  5. Bulk Operations:

    • Import all records:
      php artisan scout:import "App\Models\Post"
      
    • Queue imports for large datasets:
      php artisan scout:queue "App\Models\Post"
      

Integration Tips

  1. Customizing Searchable Data:

    • Dynamically include/exclude fields:
      public function toSearchableArray()
      {
          return $this->isAdmin()
              ? ['title' => $this->title, 'body' => $this->body, 'secret' => $this->secret]
              : ['title' => $this->title, 'body' => $this->body];
      }
      
  2. Driver-Specific Features:

    • Algolia: Use setSettings() for custom ranking:
      Post::search('query')->setSettings(['customRanking' => ['desc(created_at)']])->get();
      
    • Meilisearch/Typesense: Leverage faceting or typo tolerance:
      Post::search('query')->with(['facets' => ['categories']])->get();
      
  3. Fallback to Database:

    • Use the collection driver for local development/testing:
    SCOUT_DRIVER=collection
    
  4. Testing:

    • Mock Scout in tests:
      public function testSearch()
      {
          Scout::shouldReceive('search')->andReturn([new Post]);
          $results = Post::search('test')->get();
      }
      
  5. Performance Optimization:

    • Disable searchable for soft-deleted models:
      public function shouldBeSearchable()
      {
          return !$this->trashed();
      }
      
    • Use searchableSync() for manual syncs:
      $post->searchableSync();
      

Gotchas and Tips

Common Pitfalls

  1. Driver Mismatches:

    • Ensure your installed driver package matches the Scout version (e.g., algolia/algoliasearch-client-php@4.x for Scout v11+).
    • Fix: Check composer.json and update dependencies.
  2. Case Sensitivity:

    • Algolia is case-sensitive by default. Use typoTolerance or ignorePlurals in settings:
      Post::search('query')->setSettings(['typoTolerance' => 'min']);
      
  3. Soft Deletes:

    • Scout may not auto-sync soft-deleted models. Explicitly handle in shouldBeSearchable():
      public function shouldBeSearchable()
      {
          return !$this->trashed();
      }
      
  4. Pagination Issues:

    • Typesense/Meilisearch may return limited records due to driver quirks. Use cursor() for large datasets:
      $posts = Post::search('query')->cursor();
      
  5. Filter Syntax Errors:

    • Meilisearch/Typesense require strict filter syntax. Escape special characters:
      $posts = Post::search('query')->where('title', '!=', 'Special "Chars"')->get();
      
  6. Queue Delays:

    • Large imports may time out. Use scout:queue:
      php artisan scout:queue "App\Models\Post" --queue=search
      

Debugging Tips

  1. Log Search Queries:

    • Enable Scout logging in .env:
      SCOUT_LOG_QUERIES=true
      
    • Check storage/logs/laravel.log for raw queries.
  2. Inspect Index:

    • Use driver-specific tools:
      • Algolia: Dashboard
      • Meilisearch: http://localhost:7700/docs
      • Typesense: http://localhost:8108
  3. Handle Missing Collections:

    • Typesense/Meilisearch may throw errors if collections/indexes don’t exist. Ensure they’re created via:
      php artisan scout:import "App\Models\Post"
      
  4. Callback Debugging:

    • Add dd() in callback() to inspect raw queries:
      $posts = Post::search('query')->callback(function ($query) {
          dd($query->getQuery()); // Inspect raw query
          return $query;
      })->get();
      

Extension Points

  1. Custom Engines:

    • Extend Laravel\Scout\Engines\Engine for new drivers. Example:
      class CustomEngine extends Engine
      {
          public function update($model)
          {
              // Custom logic
          }
      }
      
  2. Override Searchable Array:

    • Dynamically modify searchable data via appendingSearchableAttributes:
      protected function appendingSearchableAttributes()
      {
          return ['slug' => $this->title];
      }
      
  3. Custom Query Builder:

    • Extend Laravel\Scout\Builder for driver-specific methods:
      class CustomBuilder extends Builder
      {
          public function customMethod()
          {
              return $this->applyCallback(function ($query) {
                  return $query->customDriverMethod();
              });
          }
      }
      
  4. Event Hooks:

    • Listen for Scout events (e.g., scout.searching) to intercept queries:
      Scout::searching(function ($query) {
          if ($query->model === Post::class) {
              $query->setSettings(['hitsPerPage' => 20]);
          }
      });
      
  5. Batch Processing:

    • Use chunk() for large datasets:
      Post::chunk(100, function ($posts) {
          foreach ($posts as $post) {
              $post->searchableSync();
          }
      });
      

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.
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
anil/file-picker
broqit/fields-ai