Integrating Elasticsearch with your Laravel application can enhance search capabilities significantly.
Step 1: Install Elasticsearch
If you haven’t installed Elasticsearch yet, you can do so by following the instructions on the official Elasticsearch website. Make sure it’s running on your local machine or server.
Step 2: Install the Elasticsearch PHP Client
You can install the Elasticsearch PHP client via Composer. Run the following command in your terminal:
bash
1 |
composer require elasticsearch/elasticsearch |
Step 3: Configure Elasticsearch in Laravel
To connect Laravel with Elasticsearch, you should create a configuration file. You can do this by creating a new config file:
- Create a configuration file at
config/elasticsearch.php
:
php
1 2 3 4 5 6 7 |
<?php return [ 'hosts' => [ env('ELASTICSEARCH_HOST', 'localhost:9200'), // Default host and port ], ]; |
- Add the Elasticsearch host configuration in your
.env
file:
plaintext
1 |
ELASTICSEARCH_HOST=localhost:9200 |
Step 4: Create a Service Provider
Create a service provider to encapsulate Elasticsearch functionality. You can do this with the following command:
bash
1 |
php artisan make:provider ElasticsearchServiceProvider |
In the ElasticsearchServiceProvider
, set up the Elasticsearch client:
php
1 |
php artisan make:provider ElasticsearchServiceProvider |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
<?php namespace App\Providers; use Elasticsearch\ClientBuilder; use Illuminate\Support\ServiceProvider; class ElasticsearchServiceProvider extends ServiceProvider { public function register() { $this->app->singleton('Elasticsearch', function ($app) { $config = $app['config']['elasticsearch']; return ClientBuilder::create()->setHosts($config['hosts'])->build(); }); } public function boot() { // } } |
Step 5: Register the Service Provider
Next, you need to register your new service provider. Open config/app.php
and add your ElasticsearchServiceProvider
to the providers
array:
php
1 2 3 4 |
'providers' => [ // Other Service Providers App\Providers\ElasticsearchServiceProvider::class, ], |
Step 6: Create an Index
Now, create an index in Elasticsearch where you will store your documents. You can do this via a controller or directly using artisan commands.
Here’s an example of how to create an index using a controller:
- Create a controller with the command:
bash
1 |
php artisan make:controller ElasticsearchController |
- In the
ElasticsearchController
, add methods to create an index:
php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; class ElasticsearchController extends Controller { public function createIndex() { $client = app('Elasticsearch'); $params = [ 'index' => 'my_index', 'body' => [ 'settings' => [ 'number_of_shards' => 1, 'number_of_replicas' => 0, ], 'mappings' => [ 'properties' => [ 'title' => ['type' => 'text'], 'content' => ['type' => 'text'], ], ], ], ]; $response = $client->indices()->create($params); return response()->json($response); } } |
Step 7: Define Routes
Define routes to access the Elasticsearch functionality in routes/web.php
:
php
1 2 3 |
use App\Http\Controllers\ElasticsearchController; Route::get('/create-index', [ElasticsearchController::class, 'createIndex'])->name('create.index'); |
Step 8: Testing the Index Creation
- Start your Laravel development server:
bash
1 |
php artisan serve |
- Visit
http://localhost:8000/create-index
in your browser. You should see a JSON response indicating the success of the index creation.
Step 9: Indexing Documents
Now, you can index documents in Elasticsearch. Update your ElasticsearchController
to include a method for indexing documents:
php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
public function indexDocument() { $client = app('Elasticsearch'); $params = [ 'index' => 'my_index', 'id' => '1', // Specify a document ID 'body' => [ 'title' => 'Sample Title', 'content' => 'This is the content of the sample document.', ], ]; $response = $client->index($params); return response()->json($response); } |
Step 10: Define a Route for Indexing Documents
Add a route to handle document indexing in routes/web.php
:
php
1 |
Route::get('/index-document', [ElasticsearchController::class, 'indexDocument'])->name('index.document'); |
Step 11: Testing Document Indexing
Visit http://localhost:8000/index-document
in your browser to index a sample document. You should see a JSON response indicating the success of the indexing.
Step 12: Searching Documents
You can also search for documents in your Elasticsearch index. Update your ElasticsearchController
to include a search method:
php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
public function searchDocument(Request $request) { $client = app('Elasticsearch'); $params = [ 'index' => 'my_index', 'body' => [ 'query' => [ 'match' => [ 'title' => $request->input('query'), ], ], ], ]; $response = $client->search($params); return response()->json($response); } |
Step 13: Define a Route for Searching Documents
Add a route for searching in routes/web.php
:
php
1 |
Route::get('/search-document', [ElasticsearchController::class, 'searchDocument'])->name('search.document'); |
Step 14: Testing Document Search
To search for documents, you can access the search route with a query parameter, for example:
bash
1 |
http://localhost:8000/search-document?query=Sample |
Summary
You have successfully integrated Elasticsearch into your Laravel application! Here’s a quick recap of the steps:
- Install Elasticsearch and the Elasticsearch PHP client.
- Create a configuration file for Elasticsearch settings.
- Create a service provider to manage the Elasticsearch client.
- Register the service provider in the app configuration.
- Create an index and methods for indexing and searching documents.
- Define routes for creating indexes and searching documents.
- Test the functionality through your browser.
- Laravel Breeze – Simple authentication starter kit
- Laravel Jetstream – Scaffolding for Laravel apps
- Laravel Passport – API authentication via OAuth2
- Laravel Sanctum – Simple API authentication
- Spatie Laravel Permission – Role and permission management
- Laravel Cashier – Subscription billing with Stripe
- Laravel Scout – Full-text search using Algolia
- Laravel Socialite – OAuth authentication (Google, Facebook, etc.)
- Laravel Excel – Excel import and export for Laravel
- Laravel Horizon – Redis queues monitoring
- Laravel Nova – Admin panel for Laravel
- Laravel Fortify – Backend authentication for Laravel
- Laravel Vapor – Serverless deployment on AWS
- Laravel Telescope – Debugging assistant for Laravel
- Laravel Dusk – Browser testing
- Laravel Mix – API for compiling assets
- Spatie Laravel Backup – Backup management
- Laravel Livewire – Building dynamic UIs
- Spatie Laravel Media Library – Manage media uploads
- Laravel Excel – Excel spreadsheet handling
- Laravel Debugbar – Debug tool for Laravel
- Laravel WebSockets – Real-time communication
- Spatie Laravel Sitemap – Generate sitemaps
- Laravel Spark – SaaS scaffolding
- Laravel Envoy – Task runner for deployment
- Spatie Laravel Translatable – Multilingual model support
- Laravel Backpack – Admin panel
- Laravel AdminLTE – Admin interface template
- Laravel Collective Forms & HTML – Simplified form and HTML generation
- Spatie Laravel Analytics – Google Analytics integration
- Laravel Eloquent Sluggable – Automatically create slugs
- Laravel Charts – Chart integration
- Laravel Auditing – Track changes in models
- Laravel JWT Auth – JSON Web Token authentication
- Laravel Queue Monitor – Monitor job queues
- Spatie Laravel Query Builder – Filter, sort, and include relationships in Eloquent queries
- Laravel Datatables – jQuery Datatables API
- Laravel Localization – Multilingual support for views and routes
- Laravel Acl Manager – Access control list manager
- Laravel Activity Log – Record activity in your app
- Laravel Roles – Role-based access control
- Spatie Laravel Tags – Tagging models
- Laravel Installer – CLI installer for Laravel
- Laravel Breadcrumbs – Generate breadcrumbs in Laravel
- Laravel Mailgun – Mailgun integration for Laravel
- Laravel Trustup Model History – Store model change history
- Laravel Deployer – Deployment automation tool
- Laravel Auth – Custom authentication guards
- Laravel CORS – Cross-Origin Resource Sharing (CORS) support
- Laravel Notifications – Send notifications through multiple channels
- Spatie Laravel Http Logger – Log HTTP requests
- Laravel Permission Manager – Manage permissions easily
- Laravel Stubs – Customize default stubs in Laravel
- Laravel Fast Excel – Speed up Excel exports
- Laravel Image – Image processing
- Spatie Laravel Backup Server – Centralize backups for Laravel apps
- Laravel Forge API – Manage servers through the Forge API
- Laravel Blade SVG – Use SVGs in Blade templates
- Laravel Ban – Ban/unban users from your application
- Laravel API Response – Standardize API responses
- Laravel SEO – Manage SEO meta tags
- Laravel Settings – Store and retrieve settings
- Laravel DOMPDF – Generate PDFs
- Laravel Turbo – Full-stack framework for building modern web apps
- Spatie Laravel Event Sourcing – Event sourcing implementation
- Laravel Jetstream Inertia – Jetstream’s Inertia.js integration
- Laravel Envoy Tasks – Task automation
- Laravel Likeable – Like/dislike functionality
- Laravel GeoIP – Determine visitor’s geographic location
- Laravel Country State City – Dropdowns for country, state, and city
- Laravel Hashids – Generate short unique hashes
- Laravel Repository – Repository pattern for Laravel
- Laravel UUID – UUID generation for models
- Spatie Laravel Medialibrary Pro – Enhanced media management
- Laravel Queue Monitor – Monitor Laravel job queues
- Laravel User Activity – Monitor user activity
- Laravel DB Snapshots – Create database snapshots
- Laravel Twilio – Twilio integration
- Laravel Roles – Role-based permission handling
- Laravel Translatable – Add translations to Eloquent models
- Laravel Teamwork – Manage teams in multi-tenant apps
- Laravel Full Text Search – Add full-text search to Laravel models
- Laravel File Manager – File and media management
- Laravel User Timezones – Automatically detect user time zones
- Laravel ChartsJS – Render charts with ChartsJS
- Laravel Stripe – Stripe API integration
- Laravel PDF Generator – PDF generation
- Laravel Elasticsearch – Elasticsearch integration
- Laravel Simple Qrcode – Generate QR codes
- Laravel Timezone – Manage timezones and conversions
- Laravel Collective API – API management for Laravel
- Laravel Rest API Boilerplate – REST API starter kit
- Laravel Multi Auth – Multi-authentication functionality
- Laravel Voyager – Admin panel for Laravel
- Laravel Voyager Database – Database manager for Voyager
- Laravel Categories – Handle categories for models
- Laravel Multitenancy – Multi-tenancy implementation
- Laravel Access Control – Advanced access control for users
- Laravel Menus – Menu management
- Laravel Translatable Routes – Multilingual route handling