Skip to main content
The Search add-on provides a query layer on top of the search indexes described in the Search reference. It wraps Laravel Scout and adds support for faceted search, filtering, sorting, and consistent response formatting using Spatie Laravel Data.

Supported Engines

The Meilisearch and Typesense PHP clients ship as dependencies of this add-on, so both drivers are available once the add-on is installed. Meilisearch also has a separate, optional add-on (see Meilisearch below) that configures index settings — it is not required to query Meilisearch through this add-on.

Installation

Require the Composer package

The package auto-discovers its Lunar\Search\SearchServiceProvider, so no additional registration is needed.

Configuration

The add-on ships its own facets configuration, merged under the same lunar.search key used by the core search config:
This config is merged, not published — there is no vendor:publish tag for it. To override or extend it, create config/lunar/search.php in the host application; any keys not present there fall back to the add-on’s defaults. The engine_map and models keys read by the core search config (see the Search reference) live in the same file. Each key under a model’s facets entry corresponds to a field in that model’s searchable index. The value is an array of per-facet-value configuration, used to attach extra data (such as a hex color) to a specific value:
label is optional and defaults to the field name. Additional keys per facet value (like hex_value above) are merged into the corresponding SearchFacetValue in the response.
engine_map, which controls which search driver is used for each model, is defined in the core Lunar search config. See the Search reference for details.

Usage

Search models using the Search facade. By default, searches are performed against Lunar\Core\Models\Product:
Search resolves to Lunar\Search\SearchManager, an Illuminate\Support\Manager. Query methods such as query(), filter(), sort(), and get() are defined on the underlying engine (Lunar\Search\Engines\AbstractEngine), not on the manager itself — calling them on the Search facade forwards the call to the resolved driver automatically. To search a different model, use the model() method:
The package detects which Scout driver is mapped for the given model via the engine_map configuration and performs the search using that driver. Results are not hydrated from the database — the raw indexed data is returned directly from the search provider.

Specifying a Driver

To explicitly use a specific search driver, call the driver() method:

Filtering

Apply filters to narrow down search results. Filters are passed as key-value pairs where the key is the field name and the value is the filter value:
Facets allow users to refine search results by selecting values within categories (e.g., brand, color, size). Set active facet selections using setFacets():
The search response includes updated facet counts that reflect the current selections, so the storefront can show how many results match each facet value. To remove a specific facet or value:

Sorting

Sort results by a specific field:
The sort format is field:direction, where direction is asc or desc. The field must be configured as sortable on the model’s indexer (see the Search reference). For Typesense, a raw sort expression can also be used:

Pagination

Control the number of results per page using the perPage() method. The default is 50:

Extending Queries

For advanced use cases, extend the search query using extendQuery():

Pipelines

Every engine runs two config-driven pipelines around its query, mirroring the cart and order pipelines in core. Stages are class names listed in lunar.search.pipelines, resolved from the container and run top to bottom through Illuminate\Pipeline\Pipeline:
The request pipeline receives a Lunar\Search\Pipelines\SearchRequest: The results pipeline receives a Lunar\Search\Pipelines\SearchResponse:

Page and per-page

AbstractEngine::page(int $page) sets the page the engine fetches, alongside the existing perPage(). Until it is called, the page resolves from the request’s page query parameter as it always has; getPage() returns whichever applies, and getPerPage() the page size. A request stage can fetch a wider window than the caller asked for (set page(1) and a larger perPage()), then a results stage slices back to requestedPage and requestedPerPage from the request passable.

Engine parameters

withParams(array $params) merges extra engine-specific request parameters on top of everything the engine builds itself, so a request stage can change retrieval without the engine knowing about it. Keys are the engine’s own parameter names: Typesense search parameters (query_by, num_typos, infix, …) for TypesenseEngine, Meilisearch request parameters (attributesToSearchOn, matchingStrategy, hybrid, …) for MeilisearchEngine. A null value removes a parameter the engine would otherwise send:
getParams() returns the merged overrides.

Meta fields

Both data objects carry a free-form meta array for engines and stages to annotate:
  • SearchHit::$meta holds the engine’s own score under score where the engine provides one: Typesense text_match, Meilisearch _rankingScore (the engine requests it with showRankingScore). Stages add their own keys.
  • SearchResults::$meta is empty by default; results stages annotate it, for example with a search id.
Both default to [], so existing calls to SearchResults::from() and SearchHit::from() are unaffected.

A custom stage

A stage is any class with a handle($passable, \Closure $next) method. This request stage restricts a search to in-stock products when the storefront asks for it through the context bag:
And this results stage annotates every hit with its display position:
The three built-in engines call pipeRequest() at the top of get() and wrap their return value in pipeResults(). A custom engine extending Lunar\Search\Engines\AbstractEngine opts in by doing the same; an engine that does not call them keeps working, but stages never run for it.

Response Format

All search engines return a Lunar\Search\Data\SearchResults object with a consistent structure:

SearchHit

Each hit contains the indexed document data and any highlights (Typesense only):

SearchHitHighlight

SearchFacet

SearchFacetValue

Handling the Response

Displaying Results

Displaying Facets

Pagination

The links property contains a standard Laravel pagination view:

Accessing Pagination Metadata

TypeScript Integration

Every response class in Lunar\Search\Data is annotated with Spatie’s #[TypeScript] attribute. If Spatie TypeScript Transformer is being used, add the add-on’s data path to the typescript-transformer.php config to generate TypeScript types for the search response classes:
The generated types are available under the Lunar.Search namespace:

Meilisearch

Meilisearch needs to know which indexed fields are filterable and sortable before it can serve faceted queries. This is a one-time (or per-schema-change) setup step, separate from running searches:
This add-on has no configuration of its own and provides a single Artisan command:
It reads config('lunar.search.models'), creates any missing Meilisearch indexes, and applies each model’s filterable and sortable attributes (as defined by its indexer — see the Search reference) to the corresponding index. It also disables typo tolerance on the fields an indexer returns from getExactMatchFields(), by setting typoTolerance.disableOnAttributes on the index. Lunar\Core\Search\ProductIndexer returns ['skus', 'skus_normalised'], so product codes only match exactly or by prefix rather than matching random tokens one or two typos away. Re-run the command after changing an indexer’s exact-match fields. To enable hybrid (semantic) search on Meilisearch, configure an embedder on the index and set its name in lunar.search.meilisearch.embedder; semantic_ratio and ranking_score_threshold then apply. Lunar does not configure the embedder itself.
The Meilisearch and Typesense engines used to query results live in the lunarphp/search package installed above. The lunarphp/meilisearch add-on only configures Meilisearch’s index settings; it is not required to run Meilisearch queries through the Search facade.

Typesense

Typesense is available as a driver (Lunar\Search\Engines\TypesenseEngine) once lunarphp/search is installed, with no separate add-on package required. Configure Typesense’s own collection schema and search parameters through Scout’s config/scout.php (the typesense.model-settings key), which controls field types for filtering, highlight and hybrid search settings, and query defaults. When the collection schema declares an auto-embedding embedding field, the engine adds a hybrid vector query to every search with a term. The query carries distance_threshold from lunar.search.typesense.vector_distance_threshold (default 0.6) so that a term with no semantic neighbours cannot pad the result set with its 200 nearest vectors; set it to 0 to send the bare k: 200 query. A vector_query search parameter in config/scout.php overrides the generated one entirely.
With a threshold in place, a nonsense query can return zero results instead of 200 padded ones. Render a zero-results state in the storefront rather than loosening the threshold to fill the page.
For product code search, declare skus and skus_normalised as string[] fields with infix: true and list both in query_by; see Product code search below for the full entries.

The skus_normalised field

Lunar\Core\Search\ProductIndexer indexes variant SKUs twice: skus as printed, and skus_normalised uppercased with every non-alphanumeric character stripped. That is what lets HAGMB prefix-match HAG-MB-32A. Both fields are part of core and are indexed whatever engine is in use. With the settings below, a shopper typing a partial code gets the whole family of that code. A request pipeline stage can go further by detecting code-like queries and restricting retrieval to these fields with withParams().

Typesense setup

Typesense needs both fields declared in the collection schema and listed in query_by, together with the position-aligned infix and num_typos lists. Both live in the host application’s config/scout.php, under typesense.model-settings:
Every entry in infix, num_typos, prefix, and query_by_weights is positional and must have exactly as many values as query_by, or Typesense rejects the request. Only infix: true in the schema enables infix search for a field; always in the search parameters then uses it. Changing the collection schema requires a reindex:
The --refresh flag drops and recreates the collection, which is what a schema change needs. Without it, Typesense keeps the old field list and the new fields are silently ignored.

Meilisearch setup

Meilisearch already prefix-matches the last word of a query, so recall of a SKU family is complete out of the box. Typo tolerance is the defect: under default settings an eight-character code returns several unrelated products per page, and none once typos are disabled on the SKU attributes. That is an index setting, not something a request can change, so the lunar:meilisearch:setup command applies it:
Re-run it after upgrading to a version of Lunar with skus_normalised, then reindex so the new field is populated:

Meilisearch page padding

Meilisearch’s default last matching strategy lists every document matching all query terms first, then fills the rest of the page with documents matching fewer terms. For a letter-only prefix such as HAG-MB, page one is the whole family followed by partial matches. This is not a ranking error, but a storefront that shows a result count will show an inflated total. Sending matchingStrategy: all, for example from a request pipeline stage through withParams(), avoids the padding.