Skip to content

Instantly share code, notes, and snippets.

@snellingio
Created August 29, 2023 18:37
Show Gist options
  • Save snellingio/97ff57cac27bee39143987aa6f63ef66 to your computer and use it in GitHub Desktop.
Save snellingio/97ff57cac27bee39143987aa6f63ef66 to your computer and use it in GitHub Desktop.
Filament highlight search
<?php
// AppServiceProvider boot
Str::macro('highlight', function ($string, $search, $highlight = '<mark class="highlight">$1</mark>', $caseSensitive = false, $minHighlightLength = 1) {
$toSearch = explode(' ', $search);
$searchable = [];
foreach ($toSearch as $key => $val) {
if (strlen($val) < $minHighlightLength) {
continue;
}
$searchable[] = preg_quote($val, '/');
}
$result = preg_replace('/(' . implode('|', $searchable) . ')/' . ($caseSensitive ? '' : 'i'), $highlight, $string);
return new HtmlString($result);
});
<?php
return $table
->query(Contact::query())
->columns([
TextColumn::make('full_name')
->sortable(['first_name', 'last_name'])
->searchable(['first_name', 'last_name'])
->formatStateUsing(
fn(string $state, Contact $record): string => ! empty($this->getTableSearch())
? Str::highlight($state, $this->getTableSearch())
: $state
)
->html(),
]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment