Laravel Elasticsearch Integration: From Routing to Search

Sercan KARA
2 min readJun 17, 2024

Photo by Ferenc Almasi on Unsplash

Introduction

In this article, we will walk you through the steps on how to set up Elasticsearch integration in your Laravel application. Elasticsearch is a highly fast, scalable, and powerful search engine, and integrating it with Laravel is a great way to add advanced search capabilities to your application.

Installation

Before you begin, make sure you have Laravel and Elasticsearch installed. Once you have Elasticsearch installed, you need to install the Laravel Scout package using the composer require elastic/scout command.

Configuring the Scout Driver

Scout is a package that is used to interact with Elasticsearch. After installing Scout, you need to open the config/scout.php file and configure the connection details for your Elasticsearch server.

return [
'default' => env('SCOUT_DRIVER', 'elasticsearch'),
'connections' => [
'elasticsearch' => [
'host' => env('ELASTICSEARCH_HOST', 'localhost'),
'port' => env('ELASTICSEARCH_PORT', 9200),
],
],
];

Making Your Models Searchable

Scout allows you to automatically make your Eloquent models searchable. To do this, you need to add a searchable method to each model. For example, for your Product model, you could do the following:

use Laravel\Scout\Searchable;
class Product extends Model implements Searchable
{
public function toSearchableArray()
{
return [
'id' => $this->id,
'name' => $this->name,
'description' => $this->description,
'price' => $this->price,
];
}
}

Creating Search Routes

Now that your models are searchable, you can create search routes. To do this, you can add the following to your routes/api.php file:

Route::get('/search/products', function (Request $request) {
$query = $request->get('q');
$results = Product::search($query)->get();
return response()->json($results);
});

This route will search Product models based on the query sent through the q request parameter and return the results in JSON format.

Conclusion

This is a basic summary of how to set up Elasticsearch integration in Laravel. For more information, please refer to the Laravel Scout documentation.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

No responses yet

Write a response