Let’s assume you have built a blog platform using Laravel and you need to build a search functionality to search through your articles and return back some results based on some input. This might get tricky especially if you have a lot of data and probably nested table relationships you need to search for, but we’ll keep it simple for this example.
By default, Laravel integrates with Elasticsearch, but that costs money. Of course you can go that route if you have to or want to… it’s definitely better, but you can also build a simpler solution (not as accurate and fast).
Simple search functionality
You might have heard of the “LIKE” SQL operator which actually searches for a specific pattern in a column. Think about it as a regular expression. So this is what we’re going to use in this tutorial.
For start, we need a form to send the data to the backend.
So this form will send a GET request to the search route we’re going to define in our routes files. We’re gonna process the data sent by the form in a controller, but first let define the route.
So we’re going to routes > web.php and define the route and name it “search”.
So now are route points to the search() method inside SearchController. Let’s define the SearchController.php.
Ok, now that we have our SearchController, we need to actually search on some Eloquent model. To keep it simple we’re gonna define our model as follows.
So our model has only 3 columns. The first one is obviously the unique auto incrementing ID, followed by ‘title’ and ‘content’. Oh, and it’s called PostModel.
Now that we have that we can go back to our controller and fill in the gaps.
So, what I did there is to get the query string from the request, check if it has more than 3 letter (or numbers/symbols) and then proceed to split all the words within it into an array. After that I removed all the array values which had less than 3 letters because be cause we don’t need to search for short words like “if”, “so”, “is”, “as”, etc. because we will get more irrelevant results.
So what’s left? Well, if there’s something left in our array, we proceed with the query. We check for each word in both “title” column and “content” column. Note that the methods used on PostModel are “where”, “orWhere” and “get”. Inside the first “where” statement I look through each word and find posts with the “title” partially matching those words, then inside the “orWhere” I do the same thing but now for the “content” column. In the end I call “get” to retrieve all the results.
It might look complicated but you can get pretty accurate results with this method. If you’re working with large amount of data and you’re website gets bombarded with tons of searches, you might want to cache the responses based on the input query string.