Boost your Laravel app’s search speed with Elasticsearch. Learn how in our step-by-step guide! Emman, January 8, 2025January 18, 2025 Elasticsearch is a powerful search and analytics engine designed to handle large-scale data efficiently. Integrating Elasticsearch with Laravel empowers you to create fast, dynamic search functionalities. This tutorial walks you through setting up Elasticsearch with Laravel to implement a robust search feature. Why Use Elasticsearch with Laravel? Speed: Perform lightning-fast searches, even with massive datasets. Scalability: Handle complex queries efficiently as your data grows. Flexibility: Supports advanced search features like fuzzy matching, pagination, and aggregations. Step 1: Install Elasticsearch For Local Development Install Elasticsearch via Docker: docker run -d --name elasticsearch \ -p 9200:9200 \ -e "discovery.type=single-node" \ docker.elastic.co/elasticsearch/elasticsearch:8.10.0 Verify installation: Navigate to http://localhost:9200 in your browser. You should see the Elasticsearch status. Step 2: Set Up Laravel Install a new Laravel project: laravel new laravel-elasticsearch cd laravel-elasticsearch Configure your .env file: ELASTICSEARCH_HOST=http://localhost:9200 Install required packages: composer require elasticsearch/elasticsearch Step 3: Connect Laravel to Elasticsearch Create a Service for Elasticsearch Edit the service file: // app/Services/ElasticsearchService.php namespace App\Services; use Elasticsearch\ClientBuilder; class ElasticsearchService { protected $client; public function __construct() { $this->client = ClientBuilder::create() ->setHosts([config('elasticsearch.host')]) ->build(); } public function getClient() { return $this->client; } } Step 4: Index Your Data Create a Model and Migration php artisan make:model Product -m Edit the migration file: // database/migrations/xxxx_xx_xx_create_products_table.php public function up() { Schema::create('products', function (Blueprint $table) { $table->id(); $table->string('name'); $table->text('description'); $table->float('price'); $table->timestamps(); }); } Run the migration and seed data: php artisan migrate use App\Models\Product; Product::create(['name' => 'Laptop', 'description' => 'High-performance laptop', 'price' => 1200]); Product::create(['name' => 'Headphones', 'description' => 'Noise-cancelling headphones', 'price' => 300]); Add Data to Elasticsearch Create a command: php artisan make:command IndexProducts Edit the command: // app/Console/Commands/IndexProducts.php namespace App\Console\Commands; use Illuminate\Console\Command; use App\Models\Product; use App\Services\ElasticsearchService; class IndexProducts extends Command { protected $signature = 'products:index'; protected $description = 'Index products to Elasticsearch'; protected $elasticsearch; public function __construct(ElasticsearchService $elasticsearch) { parent::__construct(); $this->elasticsearch = $elasticsearch; } public function handle() { $products = Product::all(); foreach ($products as $product) { $this->elasticsearch->getClient()->index([ 'index' => 'products', 'id' => $product->id, 'body' => $product->toArray(), ]); } $this->info('Products indexed successfully!'); } } Run the command: php artisan products:index Step 5: Implement Search Functionality Add a Search Endpoint Edit your routes file: // routes/web.php use App\Services\ElasticsearchService; use Illuminate\Support\Facades\Route; Route::get('/search', function (ElasticsearchService $elasticsearch) { $query = request('query'); $results = $elasticsearch->getClient()->search([ 'index' => 'products', 'body' => [ 'query' => [ 'multi_match' => [ 'query' => $query, 'fields' => ['name', 'description'], ], ], ], ]); return response()->json($results['hits']['hits']); }); Test the Search Endpoint Seed more products into the database. Use Postman or your browser to test the endpoint: http://localhost:8000/search?query=laptop Advanced Features Pagination: Use from and size parameters in the search query. Fuzzy Search: Enable typo-tolerant queries using the fuzziness parameter. Faceted Search: Add aggregations for categories, prices, etc. Conclusion Integrating Elasticsearch with Laravel unlocks powerful search capabilities for your application. With this guide, you’ve learned how to: Set up Elasticsearch locally. Index Laravel data into Elasticsearch. Implement dynamic search features. Explore Further:Enhance your Elasticsearch setup with tools like Kibana for data visualization and monitoring. Share this:FacebookX Related Discover more from Code Concepts Snippets Subscribe to get the latest posts sent to your email. Type your email… Subscribe Elastic Search Laravel PHP ElasticsearchFull-Text SearchLaravelLaravel Tutorial.