PHPackages                             designmynight/laravel-elasticsearch - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Database &amp; ORM](/categories/database)
4. /
5. designmynight/laravel-elasticsearch

ActiveLibrary[Database &amp; ORM](/categories/database)

designmynight/laravel-elasticsearch
===================================

Use Elasticsearch as a database in Laravel to retrieve Eloquent models and perform aggregations.

v12.0.1(3mo ago)3038.6k↓39.5%14[1 issues](https://github.com/designmynight/laravel-elasticsearch/issues)[5 PRs](https://github.com/designmynight/laravel-elasticsearch/pulls)MITPHPPHP ^8.2

Since Jan 3Pushed 2mo ago5 watchersCompare

[ Source](https://github.com/designmynight/laravel-elasticsearch)[ Packagist](https://packagist.org/packages/designmynight/laravel-elasticsearch)[ Docs](https://github.com/designmynight/laravel-elasticsearch)[ RSS](/packages/designmynight-laravel-elasticsearch/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (10)Dependencies (5)Versions (150)Used By (0)

laravel-elasticsearch
=====================

[](#laravel-elasticsearch)

Use Elasticsearch as a database in Laravel to retrieve Eloquent models and perform aggregations.

Build Elasticsearch queries as you're used to with Eloquent, and get Model instances in return, with some nice extras:

- Use `query`, `filter` and `postFilter` query types
- Perform geo searches
- Build and perform complex aggregations on your data
- Use the Elasticsearch scroll API to retrieve large numbers of results

Versions
--------

[](#versions)

Depending on your version of Elasticsearch you can use the following version of this package

ElasticsearchLaravel Elasticsearch&gt;= 7.0, &lt; 7.16&gt;= 6.6, &lt; 7.05&gt;= 5.0, &lt; 6.04Setup
-----

[](#setup)

Add elasticsearch connection configuration to database.php

```
'elasticsearch' => [
    'driver'   => 'elasticsearch',
    'host'     => 'localhost',
    'port'     => 9200,
    'database' => 'your_es_index',
    'username' => 'optional_es_username',
    'password' => 'optional_es_username',
    'suffix'   => 'optional_es_index_suffix',
]

```

Create or update your base Model.php class to override `newEloquentBuilder()` and `newBaseQueryBuilder()`:

```
/**
 * Create a new Eloquent builder for the model.
 *
 * @param  \Illuminate\Database\Query\Builder  $query
 * @return \Illuminate\Database\Eloquent\Builder|static
 */
public function newEloquentBuilder($query)
{
    switch ($this->getConnectionName()) {
        case static::getElasticsearchConnectionName():
            $builder = new ElasticsearchEloquentBuilder($query);
            break;

        default:
            $builder = new Illuminate\Database\Eloquent\Builder($query);
    }

    return $builder;
}

/**
 * Get a new query builder instance for the connection.
 *
 * @return \Illuminate\Database\Query\Builder
 */
protected function newBaseQueryBuilder()
{
    $connection = $this->getConnection();

    switch ($this->getConnectionName()) {
        case static::getElasticsearchConnectionName():
            $builder = new ElasticsearchQueryBuilder($connection, $connection->getQueryGrammar(), $connection->getPostProcessor());
            break;

        default:
            $builder = new Illuminate\Database\Query\Builder($connection, $connection->getPostProcessor());
    }

    return $builder;
}
```

Search
------

[](#search)

You're now ready to carry out searches on your data. The query will look for an Elasticsearch index with the same name as the database table that your models reside in.

```
$documents = MyModel::newElasticsearchQuery()
              ->where('date', '>', Carbon\Carbon::now())
              ->get();
```

Aggregations
------------

[](#aggregations)

Aggregations can be added to a query with an approach that's similar to querying Elasticsearch directly, using nested functions rather than nested arrays. The `aggregation()` method takes three or four arguments:

1. A key to be used for the aggregation
2. The type of aggregation, such as 'filter' or 'terms'
3. (Optional) A callback or array providing options for the aggregation
4. (Optional) A function allowing you to provide further sub-aggregations

```
$myQuery = MyModel::newElasticsearchQuery()
             ->aggregation(
                 // The key of the aggregation (used in the Elasticsearch response)
                 'my_filter_aggregation',

                 // The type of the aggregation
                 'filter',

                 // A callback providing options to the aggregation, in this case adding filter criteria to a query builder
                 function ($query) {
                     $query->where('lost', '!=', true);
                     $query->where('concierge', true);
                 },

                 // A callback specifying a sub-aggregation
                 function ($builder) {
                     // A simpler aggregation, counting terms in the 'status' field
                     $builder->aggregation('my_terms_aggregation', 'terms', ['field' => 'status']);
                 }
             );

$results = $myQuery->get();
$aggregations = $myQuery->getQuery()->getAggregationResults();
```

Geo queries
-----------

[](#geo-queries)

You can filter search results by distance from a geo point or include only those results that fall within given bounds, passing arguments in the format you'd use if querying Elasticsearch directly.

```
$withinDistance = MyModel::newElasticsearchQuery()
                    ->whereGeoDistance('geo_field', [$lat, $lon], $distance);

$withinBounds= MyModel::newElasticsearchQuery()
                 ->whereGeoBoundsIn('geo_field', $boundingBox);
```

Scroll API
----------

[](#scroll-api)

You can use a scroll search to retrieve large numbers of results. Rather than returning a Collection, you'll get a PHP [Generator](http://php.net/manual/en/language.generators.overview.php) function that you can iterate over, where each value is a Model for a single result from Elasticsearch.

```
$documents = MyModel::newElasticsearchQuery()
               ->limit(100000)
               ->usingScroll()
               ->get();

// $documents is a Generator
foreach ($documents as $document){
  echo $document->id;
}
```

Console
-------

[](#console)

This package ships with the following commands to be used as utilities or as part of your deployment process.

CommandArgumentsOptionsDescription`make:mapping``name`: Name of the mapping. This name also determines the name of the index and the alias.`--update`: Whether the mapping should update an existing index. `--template`: Pass a pre-existing mapping filename to create your new mapping from.Creates a new mapping migration file.`migrate:mappings``index-command`: (Optional) Name of your local Artisan console command that performs the Elasticsearch indexing. If not given, command will be retrieved from `laravel-elasticsearch` config file.`--index` : Automatically index new mapping.`--swap`: Automatically update the alias after the indexing has finished.Migrates your mapping files and begins to create the index.`index:rollback`Rollback to the previous index migration.`index:remove``index`: (Optional) Name of the index to remove from your Elasticsearch cluster.Removes an index from your Elasticsearch cluster.`index:swap``alias`: Name of alias to update. `index`: Name of index to update alias to. `old-index`: (Optional) Name of old index.`--remove-old-index`: Remove old index from your Elasticsearch cluster.Swap the index your alias points to.`index:list``--alias`: List active aliases. Pass `"*"` to view all. Other values filter the returned aliases.Display a list of all indexes in your Elasticsearch cluster.`index:copy``from`: index to copy from. `to`: the index to copy fromPopulate an index with all documents from another index### Mappings and Aliases

[](#mappings-and-aliases)

When creating a new index during a `migrate:mappings` the command will automatically create an alias based on the migration name by removing the date string. For example the migration `2018_08_03_095804_users.json` will create the alias `users`.

During the first migration an index appears in the `migrate:mappings` command will also switch the alias to the latest index mapping. The above will only happen when the alias does not already exist.

Future migrations will require you to use the `--swap` option.

###  Health Score

65

—

FairBetter than 99% of packages

Maintenance81

Actively maintained with recent releases

Popularity41

Moderate usage in the ecosystem

Community25

Small or concentrated contributor base

Maturity94

Battle-tested with a long release history

 Bus Factor1

Top contributor holds 51.4% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~23 days

Recently: every ~1 days

Total

129

Last Release

105d ago

Major Versions

5.0.x-dev → v6.3.02021-07-27

v4.2.2 → v6.3.22021-10-13

4.2.4.x-dev → v7.02022-03-16

4.2.6.x-dev → v8.0.02025-02-12

6.3.3 → 12.0.0.x-dev2026-01-29

PHP version history (5 changes)v0.1.0-alphaPHP ^7.0.0

1.1.0PHP ^7.1

v6.2.4PHP ^7.1 || ^8.0

v7.0PHP ^8.0

12.0.0.x-devPHP ^8.2

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/6871504?v=4)[Dan](/maintainers/danjohnson95)[@danjohnson95](https://github.com/danjohnson95)

![](https://avatars.githubusercontent.com/u/12199424?v=4)[Steve Porter](/maintainers/StevePorter92)[@StevePorter92](https://github.com/StevePorter92)

![](https://avatars.githubusercontent.com/u/465569?v=4)[Will Taylor-Jackson](/maintainers/willtj)[@willtj](https://github.com/willtj)

![](https://avatars.githubusercontent.com/u/9197954?v=4)[James](/maintainers/jmosul)[@jmosul](https://github.com/jmosul)

![](https://avatars.githubusercontent.com/u/1786811?v=4)[Ally](/maintainers/alasdairmackenzie)[@alasdairmackenzie](https://github.com/alasdairmackenzie)

---

Top Contributors

[![jmosul](https://avatars.githubusercontent.com/u/9197954?v=4)](https://github.com/jmosul "jmosul (72 commits)")[![robbytaylor](https://avatars.githubusercontent.com/u/2005679?v=4)](https://github.com/robbytaylor "robbytaylor (31 commits)")[![lenssoft](https://avatars.githubusercontent.com/u/9431885?v=4)](https://github.com/lenssoft "lenssoft (9 commits)")[![jeffreydevreede](https://avatars.githubusercontent.com/u/2203546?v=4)](https://github.com/jeffreydevreede "jeffreydevreede (7 commits)")[![samc05](https://avatars.githubusercontent.com/u/29915598?v=4)](https://github.com/samc05 "samc05 (5 commits)")[![alasdairmackenzie](https://avatars.githubusercontent.com/u/1786811?v=4)](https://github.com/alasdairmackenzie "alasdairmackenzie (5 commits)")[![bnagydeveloper](https://avatars.githubusercontent.com/u/13622436?v=4)](https://github.com/bnagydeveloper "bnagydeveloper (4 commits)")[![danjohnson95](https://avatars.githubusercontent.com/u/6871504?v=4)](https://github.com/danjohnson95 "danjohnson95 (3 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (2 commits)")[![JasparGupta](https://avatars.githubusercontent.com/u/23312160?v=4)](https://github.com/JasparGupta "JasparGupta (2 commits)")

---

Tags

elasticsearcheloquenteloquent-modelslaravellaravel-frameworksharedlaraveldatabaseelasticsearchmodeleloquent

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/designmynight-laravel-elasticsearch/health.svg)

```
[![Health](https://phpackages.com/badges/designmynight-laravel-elasticsearch/health.svg)](https://phpackages.com/packages/designmynight-laravel-elasticsearch)
```

###  Alternatives

[pdphilip/elasticsearch

An Elasticsearch implementation of Laravel's Eloquent ORM

145360.2k4](/packages/pdphilip-elasticsearch)[sleimanx2/plastic

Plastic is an Elasticsearch ODM and mapper for Laravel. It renders the developer experience more enjoyable while using Elasticsearch by providing a fluent syntax for mapping , querying and storing eloquent models.

508141.9k1](/packages/sleimanx2-plastic)[waad/laravel-model-metadata

A robust Laravel package for handling metadata with JSON casting, custom relation names, and advanced querying capabilities.

823.1k](/packages/waad-laravel-model-metadata)[matchory/elasticsearch

The missing elasticsearch ORM for Laravel!

3059.0k](/packages/matchory-elasticsearch)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
