-
-
Save martinandersen3d/8dbcd2a93ec81e1b4ac33dc9b4654199 to your computer and use it in GitHub Desktop.
Full Text Search In Mysql and Laravel
This file contains hidden or 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 | |
namespace App\Traits; | |
trait FullTextSearch | |
{ | |
/** | |
* Replaces spaces with full text search wildcards | |
* | |
* @param string $term | |
* @return string | |
*/ | |
protected function fullTextWildcards($term, $searchMode = null) | |
{ | |
// @ replace with white space | |
$term = str_contains('@', $term) ? str_replace('@', ' ', $term) : $term; | |
// removing symbols used by MySQL | |
$reservedSymbols = ['-', '+', '<', '>', '@', '(', ')', '~']; | |
$term = str_replace($reservedSymbols, '', $term); | |
$words = explode(' ', $term); | |
foreach ($words as $key => $word) { | |
/* | |
* applying + operator (required word) only big words | |
* because smaller ones are not indexed by mysql | |
*/ | |
if (strlen($word) >= 3) { | |
$words[$key] = !is_null($searchMode) ? str_replace('{word}', $word, $searchMode) : '+' . $word . '*'; | |
} | |
} | |
$searchTerm = implode(' ', $words); | |
return $searchTerm; | |
} | |
/** | |
* Scope a query that matches a full text search of term. | |
* | |
* @param \Illuminate\Database\Eloquent\Builder $query | |
* @param string $term | |
* @return \Illuminate\Database\Eloquent\Builder | |
*/ | |
public function scopeSearch($query, $term, $searchMode = null) | |
{ | |
$columns = implode(',', $this->searchable); | |
$query->whereRaw("MATCH ({$columns}) AGAINST (? IN BOOLEAN MODE)", $this->fullTextWildcards($term, $searchMode)); | |
return $query; | |
} | |
public function scopeSearchByScore($query, $term) | |
{ | |
$columns = implode(',', $this->searchable); | |
$searchableTerm = $this->fullTextWildcards($term); | |
return $query->addSelect($this->searchable) | |
->selectRaw("MATCH ({$columns}) AGAINST (? IN BOOLEAN MODE) AS relevance_score", [$searchableTerm]) | |
->whereRaw("MATCH ({$columns}) AGAINST (? IN BOOLEAN MODE)", $searchableTerm) | |
->orderByDesc('relevance_score'); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment