Basic Search in Laravel with Elasticsearch

Basic search in Laravel with Elasticsearch is a fundamental feature when integrating Elasticsearch into your Laravel project. To perform a basic search, follow these steps:

Step 1: Create a Model and Define Searchable Description

First, create a model in Laravel and define the searchable description for this model. The searchable description is an array containing the fields you want to search in Elasticsearch.

For example, in the Product model, you want to search based on the name and description fields.

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 2: Search Data

After defining the searchable description in the model, you can use the search() method to perform data search in Elasticsearch.

$keyword = "Laravel";

$results = Product::search($keyword)->get();

The search($keyword) method will search for records containing the keyword "Laravel" in the name and description fields of the Product model.

Step 3: Display Results

After performing the search, you can use the results to display information to the user.

foreach ($results as $result) {
    echo $result->name . ": " . $result->description;
    // Display product information or other search data
}

This allows you to present basic search results from Elasticsearch in your Laravel application.