Skip to content

Instantly share code, notes, and snippets.

@Navari
Created April 4, 2021 20:08
Show Gist options
  • Save Navari/801140b81a934cf301c9f8dcae9d87af to your computer and use it in GitHub Desktop.
Save Navari/801140b81a934cf301c9f8dcae9d87af to your computer and use it in GitHub Desktop.
Full Text Search on Laravel Models
<?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;
}
}
@Navari
Copy link
Author

Navari commented Apr 4, 2021

must be added full text index on mysql
ALTER TABLE news ADD FULLTEXT('summary', 'description', 'tags');

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment