Created
April 4, 2021 20:08
-
-
Save Navari/801140b81a934cf301c9f8dcae9d87af to your computer and use it in GitHub Desktop.
Full Text Search on Laravel Models
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\Traits; | |
trait Search | |
{ | |
/** | |
* | |
* @param string $term | |
* @return string | |
*/ | |
protected function fullTextWildcards($term) | |
{ | |
$reservedSymbols = ['-', '+', '<', '>', '@', '(', ')', '~']; | |
$term = str_replace($reservedSymbols, '', $term); | |
$words = explode(' ', $term); | |
foreach($words as $key => $word) { | |
if(strlen($word) >= 3) { | |
$words[$key] = '+' . $word . '*'; | |
} | |
} | |
return implode( ' ', $words); | |
} | |
/** | |
* | |
* @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
must be added full text index on mysql
ALTER TABLE news ADD FULLTEXT('summary', 'description', 'tags');