Created
August 29, 2023 18:37
-
-
Save snellingio/97ff57cac27bee39143987aa6f63ef66 to your computer and use it in GitHub Desktop.
Filament highlight search
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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); | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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