Laravel 5.4 #11 : Search

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:

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:

Open the controller and modify the index method:

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.

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:

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):

Open the controller and modify the index method:

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.