Skip to main content
Version: v1 (Current)

Model Searches

Advanced search adds grouped conditions to an existing model query or filters an in-memory collection. The current implementation lives in app/Services/AdvancedSearch/; it selects database or collection behavior from the input data type.

Add search to a model​

Use App\Traits\AdvancedSearchable and implement advancedSearchFieldTypes(?Project $project): array. The trait also supplies a polymorphic savedSearches relationship, an optional columnRemapper hook and processConditionGroups preprocessing. Adding the trait alone does not supply the model's field metadata or authorize searches.

Start from a query scoped to the authorized team/project. This example requires the selected project to define first_name and last_name as text attendee fields. Pass the project explicitly so those field definitions can remap the slugs to JSON-backed attendee data:

$groups = [
['conditions' => [
['field' => 'first_name', 'operator' => '=', 'value' => 'John'],
['field' => 'first_name', 'operator' => '=', 'value' => 'Jane', 'logic' => 'or'],
]],
['logic' => 'and', 'conditions' => [
['field' => 'last_name', 'operator' => '=', 'value' => 'Doe'],
]],
];

$attendees = $project->attendees()->advancedSearch($groups, $project)->get();

This describes (first_name = John OR first_name = Jane) AND last_name = Doe. Supply the group list directly to advancedSearch; a saved-search/API envelope such as search_elements must be unwrapped by its owning caller. Verify fields against the model's metadata and accepted destination schema.

Group and operator contracts​

Each group contains conditions, and a condition can itself contain conditions for nested grouping. The first group and first condition use AND regardless of a supplied logic value. Later groups prefer logic, then groupLogic, then default to and; later conditions default to and. Use explicit lower-case and/or values.

Conditions use field, operator and value where the operator requires a value. The implementation falls back from operator to the older type key and recognizes equals, notEquals and isNotBlank compatibility names. Current declared operators include comparison symbols, contains/does not contain/starts with, is empty/is not empty, in/not in and multi-value operators such as all in and any in. Support and meaning depend on field type and database versus collection path; test the intended combination rather than assuming SQL and local evaluation are identical.

Relationships and project metadata​

Database relationship paths use dot notation. The database searcher checks that each relationship exists and requires the leaf model to provide advancedSearchFieldTypes and columnRemapper. Invalid relationships or missing methods raise an InvalidArgumentException rather than becoming an empty result. Field-type lookup defaults to text when its key is absent, so incomplete metadata can change behavior. For attendees, a missing project field definition can also leave a slug unremapped: a search for first_name then addresses a nonexistent SQL column instead of attendee_fields JSON. Data containing that key alone does not create its metadata. Verify the project field definitions and pass the same project to the scope.

Negative relationship operators can use whereDoesntHave rather than a simple inequality on one related row. Test records with no related rows, multiple related rows and null values when selecting an exclusion condition. Preserve the authorized base query; search configuration is not an access-control boundary.

In-memory evaluation​

AdvancedSearch accepts an Illuminate Collection or an Eloquent/query builder and rejects other input types. buildQuery is database-only; get filters a collection or executes a database query, and exists checks the corresponding result.

The trait's inMemoryAdvancedSearch flattens each item, resolves field types and delegates to evaluateFlattened. Items must provide the expected flatten method. evaluateFlattened preprocesses conditions and returns a filtered collection, using no column-remap array. Do not assume it has the same remapping behavior as the model query scope.

The current matchesSearchConditions helper constructs a Collection-backed AdvancedSearch but calls its database-only buildQuery method, which raises an invalid-search-type exception. Use a verified collection get/exists path for local checks until that helper is corrected; do not copy it as a working predicate. The scope's searchType argument does not control the service selection, which derives from the actual input type.

Local evaluator limits​

Local field traversal splits paths on ->; it does not use the database relationship dot-path walker. Missing values resolve to null. A condition without a field returns true, so callers must validate condition shape rather than expecting malformed entries to reject every record. Empty filter/group lists also retain the initial true result.

Local Boolean composition folds conditions in their listed order. Use nested groups to express intended precedence instead of assuming arbitrary mixed AND/OR sequences match SQL precedence. Unsupported operators raise InvalidArgumentException for the selected field type; declared constants are not a universal operator allowlist.

Multi-select evaluation parses item and condition values, uses set-difference/intersection checks for all/any operators, and compares count plus differences for equality. Date/datetime conditions return false when either parsed date is invalid after handling empty/not-empty checks. Test duplicates, malformed dates and absent values when these conditions affect membership or access.

Database versus local text behavior​

The database path skips conditions with a missing/falsy field rather than adding a rejection predicate. An empty IN/NOT IN value array also adds no predicate in its current handler. Validate those inputs before applying access-related filters.

CaseDatabase pathLocal default evaluator
Empty ordinary text fieldis empty checks NULL; an empty string is not NULLUses PHP empty, including zero-like values
Empty JSON text fieldChecks NULL, empty string or literal []Depends on the extracted PHP value
Email equalityUses lower-case SQL comparisonDefault equality uses PHP loose comparison; no email-specific branch
Text contains/starts withBuilds case-insensitive LIKE patternsUses case-insensitive stripos substring/prefix checks
NOT INIncludes NULL rows; an empty array skips the predicateUses non-strict in_array and negates it

SQL text patterns incorporate the supplied value with percent wildcards. Percent and underscore in a value can therefore have LIKE pattern meaning, whereas local substring evaluation treats them as characters. Test intended literal/pattern behavior and null/zero cases before assuming the two result sets agree. These are source-level observations, not a complete parity specification.

Saved searches and callers​

Permissions and editing workflow​

Saved definitions are project resources. Listing/viewing requires view_saved_searches; creating, updating and deleting requires manage_saved_searches in the applicable project context. A saved filter does not grant permission to view its matching attendees or other records. Apply authorization to the base query and to any later export or bulk operation separately.

In the current project's attendee-management navigation, open Saved Searches to list definitions. The registered navigation target is dashboard.project.saved-searches.index; a row's edit/detail action opens dashboard.project.saved-searches.show. Use the generated routes with the selected team/project context rather than guessing a dashboard URL.

The list's Create Saved Search link opens the project's attendee screen, where the condition editor is available. Export All Saved Searches queues an export of this project's saved definitions, ordered by ID; it does not export the attendees or other records matching each definition, nor just the currently visible table rows. The controller authorizes viewAny and returns 202 when generation starts. Retrieve completed files through the project's Exports area as described in Use exports in the dashboard. Confirm the eventual export/file and its intended recipient separately; an accepted request is not a completed download. Avoid using export as a read-only status probe because finalization can email the requesting admin. Treat exported condition/view parameters as project data and review model/field mappings before importing them elsewhere.

To save or change conditions, use a model screen that mounts the AdvancedSearch controls with saved searches enabled:

  1. Build and test the groups against that screen's model and project.
  2. Choose New Saved Search, enter its name and save. Dynamic/normal group-generation options have additional group-lifecycle effects; enable them deliberately.
  3. To change an existing definition, select it in the search picker, edit the conditions and choose Update Saved Search. A screen configured with disableSavedSearch does not expose that saving workflow.
  4. Return to Saved Searches to inspect the definition's detail/settings screen. It is not the condition editor.

These labels and routes identify the current components; endpoint policy remains authoritative even if a client displays a control. The saved-search detail page currently has a Settings tab with a Name field and explicit saving (autoSave: false); it does not expose a complete condition editor there. Do not assume changing the detail-page name changes the filters.

After a change, confirm the saved model type and project, rerun representative positive/negative matches, and inspect any linked dynamic groups after their refresh job completes. Normal groups are not refreshed by the saved-search dynamic-group refresh routine. If an update returns 422 with errors.locked_by_dependant, inspect the owning dependency before retrying; repeatedly submitting the same update will not bypass the lock.

SavedSearch stores search_parameters and view_parameters as JSON, plus project ownership and searchable_type. Its create rules require a name, project ID and searchable type and accept optional parameter arrays. Update rules accept name and those parameter arrays. Array validation alone does not prove every condition/operator is valid for the selected model.

SavedSearchService resolves short model names under App\Models and rejects nonexistent classes. Its find/list queries are project-scoped and cached for 600 seconds using project tags. This is a cache of saved definitions, not search result rows. Create can also request dynamic or normal group generation inside its transaction; review the group lifecycle before enabling those options.

The observer flushes saved-search caches and dispatches refresh actions for related dynamic groups on model lifecycle events. Refresh is queued on attendee-groups-bulk, so an updated saved definition does not mean membership has already been recalculated. Inspect queue completion and resulting membership before relying on it for access decisions.

The attendee service's advancedSearch options use condition_groups, while its saved-search application passes stored search_parameters directly to the model scope. These are caller-specific shapes; do not substitute one envelope for another.

SavedSearchController registers resource authorization. Its update path checks dependency locks and returns 422 with errors.locked_by_dependant when locked, otherwise validates and updates the model. The service's update/delete methods are empty placeholders; use the implemented authorized controller/model path rather than assuming those service methods persist changes. Full tenant route binding and permission enforcement still require endpoint acceptance.

Troubleshooting​

SymptomCheck
Missing SQL column for an attendee fieldConfirm the field definition exists in this project, and pass that project so the slug is remapped to JSON data.
Unexpected or empty resultsPass the group array, not an API envelope; inspect preprocessing, field types and remapped columns.
Wrong Boolean groupingThe first logic is ignored; use nested conditions and explicit connectors for subsequent entries.
Invalid relationship errorConfirm every dot-path relationship and leaf model metadata method.
Local check throws database-only errorUse collection get/exists or the trait's flatten/evaluate path; matchesSearchConditions currently calls the wrong method.
Saved definition changed but group membership did notCheck linked dynamic groups and completion of attendee-groups-bulk; normal groups are not continuously refreshed by this routine.
Saved-search update returns a dependency lockInspect errors.locked_by_dependant and the owning dependency; do not treat it as invalid JSON or a transient queue error.
Local and database results differCheck flattening, absent metadata, null/array values, relationship exclusions and column remapping with representative fixtures.
Results cross an intended boundaryApply authorized team/project scope before searching; the search engine does not grant or enforce caller permissions.

Verification and acceptance​

The canonical equality/grouping example has passed against synthetic configured attendee fields in isolated SQLite: John Doe and Jane Doe match, other names and a matching attendee in another project do not. The same groups return the intended names through the local evaluator. Twenty-five native local-evaluator cases cover selected field/operator and malformed/empty-value behavior; they do not establish PostgreSQL parity.

A separate retained PostgreSQL fixture exercises the actual database searcher and local evaluator against synthetic text rows. It confirms that contains "%" matches all non-null text in SQL (including an empty string) but only literal-percent text locally; ordinary text is empty matches null in SQL but null and an empty string locally; empty in and not in arrays omit the SQL predicate. The explicit authorized base-project constraint remains effective in each database query. This is one case/six assertions, not a full operator, relationship or tenancy acceptance suite.

Saved-search service/policy fixtures separately cover definition permissions, project-scoped lookup/list/cache and selected refresh dispatch. They do not exercise routed model binding or complete membership recomputation. Source/fixture details and file hashes are recorded in repository docs/model-search-review-2026-10-14.md, docs/search-review-2026-10-14.md and their coverage snapshots.

Before enabling a filter for access, exports or dynamic membership, test its actual model/field metadata and destination schema against:

  • Authorized and excluded projects/principals, preserving the base query before search.
  • Positive/negative matches, absent and null/empty/zero values, literal wildcard characters and empty membership lists.
  • Nested and mixed logic, absent/multiple relationship rows, remapped fields and invalid conditions/operators.
  • Saved-definition editing/locking, cache invalidation and completed dynamic-group refresh with resulting membership checks.

Use representative fixtures on the target database and validate inputs at the owning request boundary. Database/local equality, deployment authorization and every field/operator combination remain separate acceptance requirements. The engine's predicate builder, a saved definition and a passing small fixture do not grant access or certify those outcomes.