Search with Laravel

Question

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..
}

Show source
| laravel   | php   | jquery   | mysql   | search   2016-11-24 10:11 3 Answers

Answers to Search with Laravel ( 3 )

  1. 2016-11-24 10:11

    You just put the results in a variable?

    public function search(Request $request) {
         $searchTerm = $request->search
    
         // I want to search..
         $contents = Content::where('column', '%' . $searchTerm . '%')->get();
         $blogs = BlogPost::where('column', '%' . $searchTerm . '%')->get();
         // etc..
    }
    
  2. 2016-11-24 10:11

    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.

  3. 2016-11-24 10:11

    Use merge()

     $contents = Content::where('column', '%' . $searchTerm . '%')->get();
     $blogs = BlogPost::where('column', '%' . $searchTerm . '%')->get();
     $contents->merge($blogs);
    

    https://laravel.com/docs/5.3/collections#method-merge

    another option is union:

    https://laravel.com/docs/5.3/queries#unions

Leave a reply to - Search with Laravel

◀ Go back