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

Larasearch Laravel Package

iverberk/larasearch

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require iverberk/larasearch
    

    Add the service provider to config/app.php:

    'providers' => [
        Iverberk\Larasearch\LarasearchServiceProvider::class,
    ],
    
  2. Configure Elasticsearch: Publish the config file:

    php artisan vendor:publish --provider="Iverberk\Larasearch\LarasearchServiceProvider"
    

    Update config/larasearch.php with your Elasticsearch connection details (e.g., host, port, index name).

  3. Enable a Model: Use the Searchable trait in your Eloquent model:

    use Iverberk\Larasearch\Searchable;
    
    class Product extends Model
    {
        use Searchable;
    
        protected $searchable = [
            'name', // Fields to index
            'description',
            'price',
        ];
    }
    
  4. First Use Case: Trigger an initial index:

    php artisan larasearch:index
    

    Now search via Eloquent:

    $results = Product::search('wireless headphones')->get();
    

Implementation Patterns

Core Workflows

  1. Searching: Chain Elasticsearch queries onto Eloquent:

    $products = Product::search('wireless')
        ->where('price', '<', 100)
        ->orderBy('price', 'desc')
        ->paginate(10);
    
  2. Aggregations: Group results by category:

    $results = Product::search('headphones')
        ->aggregate('category', 'terms')
        ->get();
    
  3. Autocomplete/Suggestions:

    $suggestions = Product::suggest('headpho')->get();
    
  4. Highlighting:

    $results = Product::search('wireless', ['highlight' => ['fields' => ['name']]])->get();
    

Integration Tips

  • Dynamic Fields: Use protected $searchable = ['*'] to index all non-guarded fields.
  • Relation Indexing: Define relations in $searchable:
    protected $searchable = [
        'name',
        'category.name', // Index related field
    ];
    
  • Custom Mappings: Override default mappings via searchableAs():
    public function searchableAs()
    {
        return 'products_v2';
    }
    

Common Use Cases

  • Admin Dashboards: Filter/search large datasets without N+1 queries.
  • E-commerce: Autocomplete product names, category faceting.
  • Content Management: Full-text search for articles/blogs.

Gotchas and Tips

Pitfalls

  1. Index Naming Conflicts:

    • Default index name is {model}_larasearch. Override with searchableAs() to avoid collisions.
    • Fix: Use unique index names for related models (e.g., products_v1, products_v2).
  2. Relation Indexing Lag:

    • Related fields (e.g., category.name) are indexed on model updates but may not reflect immediately.
    • Fix: Manually reindex or use php artisan larasearch:reindex {Model}.
  3. Case Sensitivity:

    • Elasticsearch is case-sensitive by default. Use analyzer: 'standard' in $searchable for case-insensitive searches:
      protected $searchable = [
          'name' => ['analyzer' => 'standard'],
      ];
      
  4. Pagination Issues:

    • Elasticsearch pagination (from/size) differs from SQL. Use paginate() instead of offset():
      // ❌ Avoid
      Product::search('term')->offset(10)->limit(10);
      
      // ✅ Use
      Product::search('term')->paginate(10);
      

Debugging

  • Check Index Status:

    php artisan larasearch:status
    
  • Log Queries: Enable debug mode in config/larasearch.php:

    'debug' => env('APP_DEBUG', false),
    

    Queries will log to storage/logs/larasearch.log.

  • Reindexing: Reindex a single model or all models:

    php artisan larasearch:reindex Product
    php artisan larasearch:reindex --all
    

Extension Points

  1. Custom Analyzers: Extend Iverberk\Larasearch\Analyzers\Analyzer to add custom text processing.

  2. Pre/Post-Index Hooks: Override searchableBeforeIndex() or searchableAfterIndex() in your model:

    public function searchableBeforeIndex(array &$data)
    {
        $data['slug'] = Str::slug($data['name']);
    }
    
  3. Bulk Operations: Use searchableBulkIndex() for large datasets:

    Product::query()->chunk(100, function ($products) {
        Product::searchableBulkIndex($products);
    });
    

Performance Tips

  • Avoid Over-Indexing: Exclude non-searchable fields (e.g., timestamps, passwords).
  • Use should for Fuzzy Search:
    Product::search('wireles', ['should' => ['fuzziness' => 2]])->get();
    
  • Cache Results: Cache frequent queries with remember():
    $results = Product::search('term')->remember(60)->get();
    
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.
facebook/capi-param-builder-php
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