Skip to content

Instantly share code, notes, and snippets.

@zzgael
Last active July 30, 2020 03:54
Show Gist options
  • Save zzgael/32f022093e51ca3b2885 to your computer and use it in GitHub Desktop.
Save zzgael/32f022093e51ca3b2885 to your computer and use it in GitHub Desktop.
Laravel 4+ very basic search Trait that you can add on any model
<?php
use Illuminate\Database\Query\Builder;
/**
* Trait MatchableTrait
* Author : Gael Debost
* Add a very basic match method to an Eloquent Model. Based on a SQL MATCH
* You need FULL TEXT Indexes in order to match fields. Somes rules :
* http://stackoverflow.com/a/1241739
* USAGE :
* Model::match("Michel Dupont, France", ["name","firstname","country"]);
* Model::match("keyword", [
* ["book_title","book_author"], ["editor_name"]
* ]);
* This only works directly on a model.
* When building a query you'll end up with an instance of Illuminate\Database\Query\Builder.
* You can then specify it as an additional argument
* Model::match("Tyler Durden", ["name","firstname"], $query);
*/
trait MatchableTrait {
/**
* @param string $expression
* @param array $indexes
* @param Builder $query
*
* @return Builder
*/
public static function match($expression,$indexes,&$query=null)
{
$expressions = preg_split("/[,\s]+/",$expression);
!$query && ($query = new self);
foreach($expressions as $words) {
$query->where(function ($query) use ($words, $indexes) {
if(!is_array($indexes[0]))
$indexes = [$indexes];
foreach($indexes as $fields)
$query->orWhereRaw(
'MATCH('.implode(",",$fields) . ') AGAINST ("'.$words.'" IN BOOLEAN MODE)'
);
});
}
return $query;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment