I would like to tweak the generated SQL query for global search. In the below example, I'm querying the user_id, firstname, lastname and email fields.
I would like to do things like:
1. Not bother searching firstname, lastname or email fields if the search term is numeric. 2. Not bother searching user_id if the search term is not numeric. 3. Do an exact match search of user_id at all times (the system defaults to LIKE '%[term]%' for each field. 4. Search for CONCAT(firstname, ' ', lastname)
I imagine I could somehow obtain the search term and modify the query, maybe in getGlobalSearchEloquentQuery(), but how?
public static function getGloballySearchableAttributes(): array { return ['user_id', 'firstname', 'lastname', 'email']; } public static function getGlobalSearchEloquentQuery(): Builder { return parent::getGlobalSearchEloquentQuery()->with(['profile'])->orderByRaw(" CASE WHEN status = 'Active' THEN 1 ELSE 2 END ")->orderBy('last_active', 'desc'); }
public static function getGloballySearchableAttributes(): array { return ['user_id', 'firstname', 'lastname', 'email']; } public static function getGlobalSearchEloquentQuery(): Builder { return parent::getGlobalSearchEloquentQuery()->with(['profile'])->orderByRaw(" CASE WHEN status = 'Active' THEN 1 ELSE 2 END ")->orderBy('last_active', 'desc'); }
Thank you!
Solution
You can overwrite the
public static function getGlobalSearchResults(string $search): Collection
public static function getGlobalSearchResults(string $search): Collection