An easy way to use the official Elastic Search client in your Laravel 5 or Lumen applications.
Install the cviebrock/laravel-elasticsearch
package via composer:
composer require cviebrock/laravel-elasticsearch
Add the service provider and facade to config/app.php
:
'providers' => [
...
Cviebrock\LaravelElasticsearch\ServiceProvider::class,
]
'aliases' => [
...
'Elasticsearch' => Cviebrock\LaravelElasticsearch\Facade::class,
]
Publish the configuration file:
php artisan vendor:publish --provider="Cviebrock\LaravelElasticsearch\ServiceProvider"
After you publish the configuration file as suggested above, you may configure Elastic Search
by adding the following to laravel .env
file
ELASTICSEARCH_HOST=localhost
ELASTICSEARCH_PORT=9200
ELASTICSEARCH_SCHEME=http
ELASTICSEARCH_USER=
ELASTICSEARCH_PASS=
If you work with Lumen, please register the LumenServiceProvider in bootstrap/app.php
:
$app->register(Cviebrock\LaravelElasticsearch\LumenServiceProvider::class);
And manually copy the configuration file to your application.
Note: don't forget to register your elasticsearch.php config in bootstrap/app.php
$app->configure('elasticsearch');
The Elasticsearch
facade is just an entry point into the ES client,
so previously you might have used:
$data = [
'body' => [
'testField' => 'abc'
],
'index' => 'my_index',
'type' => 'my_type',
'id' => 'my_id',
];
$client = ClientBuilder::create()->build();
$return = $client->index($data);
You can now replace those last two lines with simply:
$return = Elasticsearch::index($data);
That will run the command on the default connection. You can run a command on
any connection (see the defaultConnection
setting and connections
array in
the configuration file).
$return = Elasticsearch::connection('connectionName')->index($data);
Lumen users who aren't using facades will need to use dependency injection or the application container in order to get the ES service object:
// using injection:
public function handle(\Cviebrock\LaravelElasticsearch\LumenManager $elasticsearch)
{
$elasticsearch->ping();
}
// using application container:
$elasticSearch = $this->app('elasticsearch');
(Of course, DI and the application container work for Laravel as well.)
Thanks to everyone who has contributed to this project!
Please use Github for reporting bugs, and making comments or suggestions.
See CONTRIBUTING.md for how to contribute changes.
laravel-elasticsearch was written by Colin Viebrock and is released under the MIT License.
Copyright (c) 2015 Colin Viebrock