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?
Basically, the goal here should be to run this all in one query. Here goes:
For related models you can try something like this: