Rui Silva
Rui Silva

Reputation: 99

Search for partial matches in Laravel

I'm coding a search function in Laravel but I'm only able to search for the complete query which is not an ideal solution. By this I mean that if I pass a query like "lorem%20ipsum" I only get the results for "lorem ipsum" and I don't get partial matches as for "lorem" or "ipsum". Can anyone throw me some ideas on how to best accomplish this task?

This is my complete search code at the moment:

Routes.php

Route::get('{lang}/search/{query}', 'HomeController@searchPages');

HomeController.php

public function searchPages($lang, $query) {

    $searchResults = Search::acme($query, $lang);

    return View::make('search.search')
    ->with('searchResults', $searchResults);
}

models/Page.php

class Page extends Eloquent {

    public function scopeSearch($query, $search) 
    {
        return $query->where(function($query) use ($search) 
        {
            $query->where('title','LIKE', "%$search%")
                  ->orWhere('body', 'LIKE', "%$search%");
        });
    }
} 

Acme/Facades/Search.php

namespace Acme\Facades;

use Illuminate\Support\Facades\Facade;

class Search extends Facade {

    protected static function getFacadeAccessor() 
    {
        return 'search';
    }
}

Acme/Search/SearchServiceProvider.php

namespace Acme\Search;

use Illuminate\Support\ServiceProvider;

class SearchServiceProvider extends ServiceProvider {

    public function register()
    {
        $this->app->bind('search', 'Acme\Search\Search');
    }
}

Acme/Search/Search.php

namespace Acme\Search;

use Illuminate\Support\Collection;
use Page;

class Search {

    public function pages($search) 
    {
        return Page::search($search)->get();
    }

    public function acme($query, $lang) 
    {
        return new Collection(Page::join('langs', 'langs.id', '=', 'pages.lang_parent_id')
        ->where('title', 'LIKE', '%'.$query.'%')
        ->orWhere('body', 'LIKE', '%'.$query.'%')
        ->where('code', '=', $lang)
        ->get()
        ->toArray());
    }
}

Upvotes: 1

Views: 3639

Answers (1)

Ceeee
Ceeee

Reputation: 1442

you need to loop through your search text and build you eloquent, for example:

$db_query = Page::join('langs', 'langs.id', '=', 'pages.lang_parent_id');
$my_search_text_arr = explode(' ',$query);

$first = true
for_each($my_search_text_arr as $my_search_text){
   if($first){
      $db_query = $db_query->where('title', 'LIKE', '%'.$my_search_text.'%');
      $first = false;
   }else{
      $db_query = $db_query->orWhere('title', 'LIKE', '%'.$my_search_text.'%');
   }
}

 return new Collection($db_query
        ->where('code', '=', $lang)
        ->get()
        ->toArray());

Upvotes: 1

Related Questions