Install and Configure Elasticsearch in Laravel

To install and configure Elasticsearch in Laravel, follow these steps:

Step 1: Install Elasticsearch

Firstly, you need to install Elasticsearch on your server or use Elasticsearch cloud service like Elastic Cloud. Visit the Elasticsearch official website to download the appropriate version and follow the installation instructions.

Step 2: Install Elasticsearch Package for Laravel

Next, install the Elasticsearch package for Laravel. There are various packages that support Elasticsearch in Laravel, but one popular package is "Laravel Scout". To install Laravel Scout, open the terminal and run the following command:

composer require laravel/scout

Step 3: Configure Elasticsearch in Laravel

After installing Laravel Scout, you need to configure it to use Elasticsearch as the default search engine. Open the .env file of Laravel and add the following configuration parameters:


Where SCOUT_DRIVER defines the search engine that Laravel Scout uses and SCOUT_ELASTICSEARCH_HOSTS specifies the Elasticsearch URL that Scout will connect to.

Step 4: Run Migration

Next, run the migration to create the "searchable" table for the models you want to search in Elasticsearch. Use the following command:

php artisan migrate

Step 5: Define Model and Assign Searchable Description

Finally, in the model you want to search, add the Searchable trait and define the searchable description for each model. For example:

use Laravel\Scout\Searchable;

class Product extends Model
    use Searchable;

    public function toSearchableArray()
        return [
            'id' => $this->id,
            'name' => $this->name,
            'description' => $this->description,
            // Add other searchable fields if needed

Step 6: Synchronize Data with Elasticsearch

After configuring and defining the searchable models, run the command to synchronize data from your database to Elasticsearch:

php artisan scout:import "App\Models\Product"

Once completed, Elasticsearch has been integrated into Laravel, and you can start using its search feature in your application.