Created
May 27, 2018 03:51
-
-
Save tisuchi/c2cd5af6c1e77fd60892800a38b53930 to your computer and use it in GitHub Desktop.
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 | |
namespace App; | |
trait FullTextSearch | |
{ | |
/** | |
* Replaces spaces with full text search wildcards | |
* | |
* @param string $term | |
* @return string | |
*/ | |
protected function fullTextWildcards($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] = '+' . $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) | |
{ | |
$columns = implode(',',$this->searchable); | |
$query->whereRaw("MATCH ({$columns}) AGAINST (? IN BOOLEAN MODE)" , $this->fullTextWildcards($term)); | |
return $query; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment