In a blog it is important that there is a search engine. A search engine makes easier for our visitors to find content that is of interest to them. Today we will add it to the blog that we are developing. We will see how to add two types of search engines, one simple and another full-text search.
Simple search
First, we will add the search form to the view. Open the file resources/views/posts.blade.php and add this:
1 2 3 4 5 6 |
... {{ Form::open(['route' => ['posts.index'], 'method' => 'GET']) }} <p>{{ Form::text('search', old('search'), array('placeholder'=>'Search')) }}</p> <p>{{ Form::submit('Search') }}</p> {{ Form::close() }} ... |
The form is sent to the route called posts.index (we now add the name because currently it doesn’t have it) through the HTTP GET.
Modify in the routes file the index route to add the name:
1 |
Route::get('/posts', 'PostsController@index')->name('posts.index'); |
Open the controller and modify the index method:
1 2 3 4 5 6 7 |
public function index() { $posts = Post::where('title', 'like', '%'.Input::get('search').'%') ->orWhere('body', 'like', '%'.Input::get('search').'%') ->orderBy('id', 'desc')->paginate(6); return view('posts', ['posts' => $posts]); } |
What it does is to return the posts that contain, or in the title or in the body, what we have put in the search engine.
Full-text search
This type of search is faster than the previous one, since it is based on indexes.
To add this type of search, we will add a Laravel package called Eloquence.
1 |
composer require sofa/eloquence |
Once it is done, we have to register it in our app. Open the config/app.php file and add this line to $providers array:
1 2 3 4 |
'providers' => [ ... 'Sofa\Eloquence\ServiceProvider', ], |
Open the model and add these lines (add Eloquence to be able to use it later and add the columns that will be searched by default):
1 2 3 4 5 6 7 8 9 10 11 12 |
... use Sofa\Eloquence\Eloquence; class Post extends Model { ... use Eloquence; // default fields to search protected $searchableColumns = ['title', 'body']; ... } |
Open the controller and modify the index method:
1 2 3 4 5 |
public function index() { $posts = Post::search(Input::get('search'))->orderBy('id', 'desc')->paginate(6); return view('posts', ['posts' => $posts]); } |
We use the search method of Eloquence package, passing the value of the search input.
To find more information about this package, you can find it in its documentation.
-
– https://packagist.org/packages/sofa/eloquence
– https://github.com/jarektkaczyk/eloquence/wiki/Builder-searchable-and-more