spatie/laravel-searchable
Structured, case-insensitive search across Eloquent models and other sources. Register models/attributes (or custom search aspects) and get grouped, typed results with titles and URLs—ideal for building unified search pages in Laravel apps.
Install the package via Composer:
composer require spatie/laravel-searchable
Begin by identifying models or external data sources you want searchable—common examples include User, BlogPost, or API-backed entities. For models, implement the Spatie\Searchable\Searchable interface and define a getSearchResult() method that returns a SearchResult object (with title, URL, and the model instance). Then, in your search logic (e.g., controller), instantiate new Search(), register models (and optionally specify attributes like name or title) via registerModel(), and call ->search('query').
registerModel(Model::class, 'field1', 'field2') for simple cases, or pass an array for multiple attributes. For advanced control, pass a closure to receive a ModelSearchAspect instance and chain scopes (->active()), eager loads (->with()), or exact/partial match definitions (->addExactSearchableAttribute(), ->addSearchableAttribute()).SearchAspect and implement getResults(string $term): Collection to integrate non-model sources (e.g., external APIs, files, cached data). Register them via registerAspect(CustomAspect::class).groupByType() on the SearchableCollection to separate results by source. Override the default type label by adding a public $searchableType property on your model or aspect class.limitAspectResults(int $count) before search() to cap results per aspect—useful for performance or UI balance.->active()) to narrow results early.addExactSearchableAttribute(), note that leading/trailing whitespace in database values will break matches (fixed in v1.13.1); consider ->whereRaw('TRIM(column) = ?', $term) if needed.utf8mb4_unicode_ci).dd($searchResults) early—inspect the SearchResult objects’ structure, and verify your getSearchResult() methods return valid title, url, and model properties.SearchAspect, SearchableCollection) or tailoring Blade render logic. You can also add custom filters or scoring via aspect closures.How can I help you explore Laravel packages today?