senty senty - 12 days ago 5
jQuery Question

Search with Laravel

I am trying to make a search for multiple models. I have set up the route and html form and I am successfully receiving the data in my controller. Now, I want to query multiple columns and get the result as an eloquent or array.

What is the proper way of achieving this?

public function search(Request $request) {
$searchTerm = $request->search

// I want to search..
Content::where('value', '%' . $searchTerm . '%')->get();
BlogPost::where('value', '%' . $searchTerm . '%')->get();
// etc..
}

Answer

First, add like to the queries. Then, if you want an array, use toArray() method and array_merge() to merge results:

$result1 = Content::where('value', 'like', '%'.$searchTerm.'%')->get()->toArray();
$result2 = BlogPost::where('value', 'like', '%'.$searchTerm.'%')->get()->toArray();
$result = array_merge($result1, $result2);

If you want to get a collection, just get the data and merge it with merge() helper.

Comments