Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel full text search

I'm trying to implement a full text search query to the database. This is in the specification that my client sent me:

"The free text search limits the result of the data table to records with a matching first
name, last name, country, city, state, or zip code. If several words are input,
each word must match one of the columns for a record to be visible."

I made some very ugly spaghetti code in my controller to try if it works:

public function search($searchTerms){
        $searchTerms = explode(' ', $searchTerms);
        $results = array();
        foreach ($searchTerms as $searchTerm) {
            if (!People::where('firstname', 'LIKE', '%'.$searchTerm.'%')->get()->isEmpty()) {
                array_push($results, People::where('firstname', 'LIKE', '%'.$searchTerm.'%')->get());
            }
            else if (!People::where('lastname', 'LIKE', '%'.$searchTerm.'%')->get()->isEmpty()) {
                array_push($results, People::where('lastname', 'LIKE', '%'.$searchTerm.'%')->get());
            }
        }
        return $results;
    }

And this is my call to this function:

$data->people = $this->search(Input::get('search'));

The problem is that if there is no search input, I use this to get all data:

$data->people = People::orderBy($order)->paginate(10);

And by getting the search results as an array, I get the following error in my views:

Undefined property: Illuminate\Database\Eloquent\Collection::$firstname (View: /home/projects/pplproject/app/views/index.blade.php) 

How should this be implemented in the Laravel way?

like image 418
Peter Avatar asked Dec 25 '22 22:12

Peter


1 Answers

Basically, the goal here should be to run this all in one query. Here goes:

$searchTerms = explode(' ', $searchTerms);
$query = People::query();

foreach($searchTerms as $searchTerm){
    $query->where(function($q) use ($searchTerm){
        $q->where('firstname', 'like', '%'.$searchTerm.'%')
        ->orWhere('lastname', 'like', '%'.$searchTerm.'%')
        ->orWhere('country', 'like', '%'.$searchTerm.'%')
        // and so on
    });
}

$results = $query->get();

For related models you can try something like this:

foreach($searchTerms as $searchTerm){
    $query->where(function($q) use ($searchTerm){
        $q->where('firstname', 'like', '%'.$searchTerm.'%')
        ->orWhereHas('relationName', function($relation) use ($searchTerm){
            $relation->where('relation_attribute', 'like', '%'.$searchTerm.'%');
        });
    });
}
like image 125
lukasgeiter Avatar answered Dec 28 '22 18:12

lukasgeiter