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

abo/larasearch

Laravel package that adds simple, lightweight search to your app. Provides a straightforward API to index and query models, helping you build basic site or admin search without heavy external services or complex setup.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require abo/larasearch
    

    Publish the config file (if needed):

    php artisan vendor:publish --provider="Abo\Larasearch\LarasearchServiceProvider"
    
  2. Basic Usage:

    • Search Model: Add the Searchable trait to your Eloquent model:
      use Abo\Larasearch\Searchable;
      
      class Product extends Model
      {
          use Searchable;
      }
      
    • Define Searchable Fields: Override the searchableFields() method:
      protected function searchableFields()
      {
          return ['name', 'description', 'sku'];
      }
      
    • Run Search:
      $results = Product::search('query')->get();
      
  3. First Use Case: Implement a search feature in a controller:

    public function search(Request $request)
    {
        $query = $request->input('q');
        $products = Product::search($query)->paginate(10);
        return view('products.search', compact('products'));
    }
    

Implementation Patterns

Common Workflows

  1. Basic Search:

    // Simple keyword search
    $results = Model::search('term')->get();
    
  2. Advanced Querying:

    • Combine with Eloquent query builder:
      $results = Model::search('term')
          ->where('category', 'electronics')
          ->orderBy('created_at', 'desc')
          ->get();
      
    • Use orSearch for multiple terms:
      $results = Model::search('term1')->orSearch('term2')->get();
      
  3. Pagination & Sorting:

    $results = Model::search('term')->paginate(15);
    $results = Model::search('term')->orderBy('name')->get();
    
  4. Full-Text Search:

    • Ensure your database supports full-text indexing (e.g., MySQL FULLTEXT).
    • Define fields in searchableFields() for full-text search.
  5. Integration with API:

    Route::get('/api/search', function (Request $request) {
        return Model::search($request->query('q'))->paginate(20);
    });
    
  6. Search in Relationships:

    • Use with() to eager-load relationships:
      $results = Model::with('category')->search('term')->get();
      
  7. Custom Search Logic:

    • Override search() method in your model:
      public function scopeCustomSearch($query, $term)
      {
          return $query->where(function($q) use ($term) {
              $q->where('name', 'like', "%{$term}%")
                ->orWhere('description', 'like', "%{$term}%");
          });
      }
      

Gotchas and Tips

Pitfalls

  1. Database Compatibility:

    • Full-text search may not work as expected on SQLite. Use MySQL/PostgreSQL for advanced features.
    • Ensure your searchable fields are indexed in the database for performance.
  2. Case Sensitivity:

    • Searches are case-insensitive by default. For case-sensitive searches, modify the underlying query.
  3. Performance:

    • Avoid searching on large text fields (e.g., body) without proper indexing.
    • Limit the number of searchable fields to improve speed.
  4. Special Characters:

    • Wildcards (%) in queries may not work as expected. Escape or handle them manually:
      $query = str_replace(['%', '_'], ['\%', '\_'], $request->input('q'));
      
  5. Config Overrides:

    • If the package publishes a config file, ensure you review and customize it (e.g., default search fields, query modifiers).

Debugging

  1. Log Queries: Enable Laravel's query logging to inspect generated SQL:

    DB::enableQueryLog();
    $results = Model::search('term')->get();
    dd(DB::getQueryLog());
    
  2. Check Field Names:

    • Typos in searchableFields() will silently fail. Validate field names against your database schema.
  3. Test with Simple Queries: Start with single-word searches to isolate issues before testing complex queries.

Tips

  1. Extend Searchable Trait:

    • Create a base model with shared search logic:
      class SearchableModel extends Model
      {
          use Searchable;
      
          protected function searchableFields()
          {
              return ['global_search_field'];
          }
      }
      
  2. Use Events:

    • Trigger events after search (e.g., log searches, update analytics):
      Model::search('term')->each(function ($model) {
          event(new SearchPerformed($model, 'term'));
      });
      
  3. Combine with Scout:

    • For large-scale applications, consider using Laravel Scout alongside this package for distributed search.
  4. Custom Analyzers:

    • If using MySQL, leverage custom full-text analyzers for better search relevance.
  5. Fallback for Empty Results:

    • Provide a fallback response when no results are found:
      $results = Model::search($term)->get();
      return $results->isEmpty() ? response()->json(['message' => 'No results found']) : $results;
      
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.
calmfox/watch-sylius
damienfern/grpc-symfony-bundle
atoolo/index-bundle
atoolo/genai-bundle
coprotoai/laravel-ticket
davidjln/llm-carbon-bundle
cryonighter/valid-request-bundle
coolms/taxonomy-bundle
coolms/field-bundle
articulate-orm/symfony
aaix/laravel-tall-architect
ephoto/akeneo-connector
emmanuelballery/eb-plantumlbundle
emielburgman/symfony-visitor-beacon
emielburgman/symfony-visit-storage
emielburgman/symfony-security-headers
emielburgman/symfony-log-viewer
emarref/xdebug-bundle
emarref/pubnub-bundle
elriseio/finance-money-bundle