PHPackages                             michaeljennings/laralastica - 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. [Search &amp; Filtering](/categories/search)
4. /
5. michaeljennings/laralastica

ActiveLibrary[Search &amp; Filtering](/categories/search)

michaeljennings/laralastica
===========================

A laravel package that allows you to search eloquent results using elasticsearch.

v3.3.1(6y ago)102.9k6[4 issues](https://github.com/michaeljennings/laralastica/issues)[1 PRs](https://github.com/michaeljennings/laralastica/pulls)MITPHPPHP ^7.0

Since Jun 10Pushed 3y ago2 watchersCompare

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

READMEChangelog (10)Dependencies (12)Versions (53)Used By (0)

Laralastica [![Build Status](https://camo.githubusercontent.com/c3a92627547ec4eebc6f9fd3d3306c0ae31de949de3df741b9690252d4eacd80/68747470733a2f2f7472617669732d63692e6f72672f6d69636861656c6a656e6e696e67732f6c6172616c6173746963612e7376673f6272616e63683d6d6173746572)](https://travis-ci.org/michaeljennings/laralastica) [![Latest Stable Version](https://camo.githubusercontent.com/3a1d03ace4ada0b693ba037c005c166958dbb2bbe5b8fa961866233e70b334da/68747470733a2f2f706f7365722e707567782e6f72672f6d69636861656c6a656e6e696e67732f6c6172616c6173746963612f762f737461626c65)](https://packagist.org/packages/michaeljennings/laralastica) [![Coverage Status](https://camo.githubusercontent.com/99349e82ba46ada123b148fb26ce1130246ed1876f45523f8742f915e8850d03/68747470733a2f2f636f766572616c6c732e696f2f7265706f732f6769746875622f6d69636861656c6a656e6e696e67732f6c6172616c6173746963612f62616467652e7376673f6272616e63683d6d6173746572)](https://coveralls.io/github/michaeljennings/laralastica?branch=master) [![License](https://camo.githubusercontent.com/27fb47289b8b071b12f2c02b373dbdbc7d86f44853fb2359b8cd97b39af50b07/68747470733a2f2f706f7365722e707567782e6f72672f6d69636861656c6a656e6e696e67732f6c6172616c6173746963612f6c6963656e7365)](https://packagist.org/packages/michaeljennings/laralastica)
==============================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================

[](#laralastica----)

A laravel 5 package that adds the ability to search eloquent models using elasticsearch results, it also handles indexing and removing documents when you save or delete models.

- [Installation](#installation)
    - [Configuration](#configuration)
- [Usage](#usage)
- [Building Your Index](#building-your-index)
- [Searching](#searching)
    - [Searching Soft Deleted Records](#searching-soft-deleted-records)
    - [Searching Without the Searchable Trait](#searching-without-the-searchable-trait)
    - [Limit Results](#limit-results)
    - [Offsetting Results](#offsetting-results)
    - [Sorting Results](#sorting-results)
- [Queries](#queries)
- [Filters](#filters)
- [Paginate Results](#paginate-results)
- [The Result Collection](#the-result-collection)

Upgrading from 3.0 to 3.1+
--------------------------

[](#upgrading-from-30-to-31)

When hitting the `search` method on a model the query builder will return an instance of `Michaeljennings\Laralastica\Eloquent\ResultCollection` instead of `Illuminate\Database\Eloquent\Collection`.

```
// This will return an instance of Michaeljennings\Laralastica\Eloquent\ResultCollection
Model::search(function(Builder $builder) {
  $builder->matchAll();
})->get();
```

This is useful as you get access to the `totalHits`, `maxScore`, and `totalTime` methods.

However if you want to use the default collection you may override the `newCollection` method on your model and return the collection instance you need.

```
/**
 * Create a new database notification collection instance.
 *
 * @param array $models
 * @return ResultCollection
 */
public function newCollection(array $models = [])
{
    return new Illuminate\Database\Eloquent\Collection($models);
}
```

Installation
------------

[](#installation)

Check the table below to see which version you will need.

LaralasticaLaravelElasticsearchPHP3.x^5.16.x^7.02.x^5.12.x-5.x^5.5.9To install through composer either run `composer require michaeljennings/laralastica` or add the package to you composer.json.

```
"michaeljennings/laralastica": "^3.1"
```

For Laravel 5.5 and upwards, the service provider and facade will be loaded automatically.

For older versions of Laravel, you will need to add the laralastica service provider into your providers array in `config/app.php`.

```
'providers' => [

  'Michaeljennings\Laralastica\LaralasticaServiceProvider'

];
```

The package also comes with a facade, to use it add it to your aliases array in `config/app.php`.

```
'aliases' => [

  'Laralastica' => 'Michaeljennings\Laralastica\Facades\Laralastica',

];
```

### Configuration

[](#configuration)

Finally publish the package config using `php artisan vendor:publish`. Once the config has published you can edit the `config/laralastica.php' file to set your elasticsearch connection.

The package comes with 2 drivers: elastica, and null. By default the package will use the elastica driver. The null driver is mainly testing purposes where you don't want to have an elasticsearch instance running.

```
'driver' => 'elastica',
```

As of laralastica 3.0 we now use multiple indexes, rather than multiple types in one index. To see why check this post [about the removal of types](https://www.elastic.co/guide/en/elasticsearch/reference/current/removal-of-types.html).

If you are using multiple environments (production, staging, testing etc.) you can define a index prefix in the config. This will the be added to each index when searcing, adding documents etc.

```
'index_prefix' => 'testing_',
```

Finally you need to configure your elasticsearch connection. Out of the box the package comes ready to support multiple connections.

However you can pass through any of the parameters the elastica client can receive, check the [elastica documentation](https://github.com/ruflin/Elastica) for more information.

To set the connection you wish to use either enter the host and port you want to connect to, or the url to connect with.

```
'drivers' => [
  'elastica' => [
    'servers' => [
      [
        'host' => 'localhost',
        'port' => 9200
      ],
      [
        'url' => 'https://user:pass@your-search.com/'
      ]
    ],
  ]
]
```

Usage
-----

[](#usage)

To get started using the package simply add the `Searchable` trait to the models you want to index and search.

```
use Illuminate\Database\Eloquent\Model;
use Michaeljennings\Laralastica\Searchable;

class Foo extends Model
{
	use Searchable;
}
```

Once you have added the trait it will use [model events](http://laravel.com/docs/5.0/eloquent#model-events) to watch when a model is saved, deleted or restored and will add or delete the elasticsearch document as appropriate.

### Set Elasticsearch Index

[](#set-elasticsearch-index)

To set the elasticsearch index for the model use the `getIndex` method to return the name of the index. By default this will return the table name the model is using. The index must be lowercase.

```
public function getIndex()
{
	return 'foo';
}
```

### Set Elasticsearch Key To Index By

[](#set-elasticsearch-key-to-index-by)

To set the value to index the elasticsearch documents by use the 'getSearchKey' method to return the key. By default this will return the primary key of the model.

```
public function getSearchKey()
{
	return $this->key;
}
```

### Set the Attributes to Index

[](#set-the-attributes-to-index)

To set which attributes should be indexed for the model use the `getIndexableAttributes` method. The attributes must be returned as an array of key value pairs. By default all of the models attributes are indexed.

```
public function getIndexableAttributes()
{
	return [
		'foo' => $this->bar,
	];
}
```

### Type Cast Attributes

[](#type-cast-attributes)

In elasticsearch each index has a mapping type which will determine how records are indexed, this means that you have to supply each object in the same format. To this we can use the `casts` property that is supplied by laravel.

```
protected $casts = [
	'price' => 'float',
	'active' => 'bool',
	'quantity' => 'int',
	'name' => 'string'
];
```

Occasionally you may find yourself wanting to cast values slightly differently for your elasticsearch records. To that you can define the `laralasticaCasts` property and this will allow you to override the casts property.

```
protected $casts = [
	'price' => 'float',
];

protected $laralasticaCasts = [
	'price' => 'string',
];
```

Building Your Index
-------------------

[](#building-your-index)

If you already have data you in your database and you want to index it you can use the `laralastica:index` artisan command.

### Defining Models To Index

[](#defining-models-to-index)

To get started you'll need to set the models you want to index in the indexable section of the `laralastica.php` config file.

By default the package is setup to index the standard `App\User` class.

```
'indexable' => [
    'users' => \App\User::class,
]
```

To add a new model we need to set a custom key to reference this model by, this will allow us to index just that model if we want to.

Then the value needs to be the fully qualified path of the model class.

For example if we wanted to index a products model we could do:

```
'indexable' => [
    'users' => \App\User::class,
    'products' => \App\Product::class,
]
```

Occasionally you may want to index relational data, if you have a large database this can take a long time to lazy load the relations. To get around this you can specify the relations to bring when indexing.

```
'indexable' => [
    'users' => \App\User::class,
    'products' => [
        'model' => \App\Product::class,
        'with' => [
            'category' => function($query) {
                $query->with('subcategories');
            }
        ]
    ]
]
```

### Indexing

[](#indexing)

If you want to index all of the models you have setup then you can run:

```
php artisan laralastica:index

```

To run a specific index run:

```
php artisan laralastica:index [your-index]

// For our example above it would be
php artisan laralastica:index products

```

If you are indexing a large amount of data you may want to push it to the queue, you can do so by providing the queue option

```
php artisan laralastica:index --queue

```

Searching
---------

[](#searching)

To run a search use the `search` method. This uses a closure to search the elasticsearch type and then gets the results and adds a where in query from the results.

The first parameter for the `search` method is a Closure which gets passed an instance of the laralastica query builder.

The second parameter is the column for the where in query, this defaults to 'id'.

The third parameter is a boolean indicating if the query should be ordered by the order of the elasticsearch results.

```
Foo::search(function(Builder $query) {

	$query->matchAll();

}, 'foo', true)->get();
```

You can also set whether the query must, should or must not match the value you are searching for.

```
Foo::search(function(Builder $query) {

	$query->match('foo', 'bar')->must();
	$query->terms('bar', ['baz'])->should();
	$query->wildcard('baz', 'qux*', 1.0)->mustNot();

})->get();
```

You may also chain any Laravel query builder methods before or after searching.

```
Foo::where('foo', 'bar')->search(function(Builder $query) {

	$query->match('foo', 'bar');

})->orderBy('baz')->get();
```

### Searching Soft Deleted Records

[](#searching-soft-deleted-records)

By default laralastica will delete the elasticsearch record when a model is deleted.

Occasionally you may want to search against your soft deleted records, to do that you implement the `SearchSoftDeletes` trait instead of the `Searchable` trait in your model.

```
use Illuminate\Database\Eloquent\Model;
use Michaeljennings\Laralastica\SearchSoftDeletes;

class Foo extends Model
{
	use SearchSoftDeletes;
}
```

This adds adds two new methods - `searchWithTrashed` and `searchOnlyTrashed`.

Both methods take the same parameters as the search method, but `searchWithTrashed` will search both soft deleted and non-soft deleted results, and `searchOnlyTrashed` will only get soft deleted results.

To only search for non-soft deleted results just use the `search` method as usual.

### Searching Without the Searchable Trait

[](#searching-without-the-searchable-trait)

It is also possible to use Laralastica without using the searchable trait. To do so you can either dependency inject the class via its contract, use the provided Facade, or use the `laralastica` helper method.

```
class Foo
{
	public function __construct(Michaeljennings\Laralastica\Contracts\Laralastica $laralastica)
	{
		$this->laralastica = $laralastica;
	}

	public function foo()
	{
		$laralastica = Laralastica::search();
		$laralastica = laralastica();
	}
}
```

To run a new query use the `search` method. This takes two parameters:

- The index/indices you are searching in
- The query to be run

```
$laralastica->search('foo', function($query) {
	$query->matchAll();
});
```

To search across multiple elasticsearch indices simply pass an array of indices as the first parameter.

```
$laralastica->search(['foo', 'bar], function($query) {
	$query->matchAll();
});
```

To get a paginated list of results hit the `paginate` method and the amount to paginate by.

```
$laralastica->paginate('foo', function($query) {
	$query->matchAll();
}, 15);
```

### Limit Results

[](#limit-results)

By default the results will be limited to the size set in the `laralastica.php` config file. However you can override it by hitting the `size` method.

```
$laralastica->search('foo', function($query) {
	$query->size(50);
});
```

### Offsetting Results

[](#offsetting-results)

It is also possible to provide an offset by hitting the `from` method.

```
$laralastica->search('foo', function($query) {
	$query->from(10);
});
```

### Sorting Results

[](#sorting-results)

By default we sort the results by their score in descending order. You can override this by hitting the sort method.

```
$laralastica->search('foo', function($query) {
    // Sort by id in ascending order
    $query->sort('id');
    // Sort by id in descending order
    $query->sort('id', 'desc');
    // Sort by multiple fields
    $query->sort([
        '_score',
        'id' => 'desc'
    ]);
});
```

Queries
-------

[](#queries)

The elasticsearch queries are powered by the great [elastica package](https://github.com/ruflin/Elastica).

There are some preset queries on the query builder, but it is also possible to create an instance of an elastica query and pass that through.

### Available Queries

[](#available-queries)

A list of the available queries can be found below.

Each of the queries can optionally be passed a callback as the final parameter which will allow you to access the raw elastica query.

### Bool Query

[](#bool-query)

```
$laralastica->search('foo', function($query) {

    $query->bool(function($query) {
        $query->match('foo', 'bar');
    });

});
```

### Common Query

[](#common-query)

```
$laralastica->search('foo', function($query) {

    $query->common('baz', 'qux', 1.0);
    $query->common('baz', 'qux', 1.0, function($commonQuery) {
        $commonQuery->setMinimumShouldMatch(5);
    });

});
```

### Exists Query

[](#exists-query)

```
$laralastica->search('foo', function($query) {

    $query->exists('baz');

});
```

### Fuzzy Query

[](#fuzzy-query)

```
$laralastica->search('foo', function($query) {

    $query->fuzzy('baz', 'qux');
    $query->fuzzy('baz', 'qux', function($fuzzyQuery) {
        $fuzzyQuery->setFieldOption('fuzziness', 2);
    });

});
```

### Match Query

[](#match-query)

```
$laralastica->search('foo', function($query) {

    $query->match('baz', 'qux');
    $query->match('baz', 'qux', function($matchQuery) {
        $matchQuery->setFieldBoost('foo');
    });

});
```

### Match All Query

[](#match-all-query)

```
$laralastica->search('foo', function($query) {

    $query->matchAll();

});
```

### Query String Query

[](#query-string-query)

```
$laralastica->search('foo', function($query) {

    $query->queryString('testing');
    $query->queryString('testing', function($queryStringQuery) {
        $queryStringQuery->setDefaultField('foo');
    });

});
```

### Range Query

[](#range-query)

```
$laralastica->search('foo', function($query) {

    $query->queryString('foo', ['gte' => 1, 'lte' => 20]);
    $query->queryString('foo', ['gte' => 1, 'lte' => 20], function($rangeQuery) {
        $rangeQuery->setParam('foo', ['gte' => 1, 'lte' => 20, 'boost' => 1]);
    });

});
```

### Regular Expression Query

[](#regular-expression-query)

```
$laralastica->search('foo', function($query) {

    $query->regexp('foo', 'testing');

});
```

### Term Query

[](#term-query)

```
$laralastica->search('foo', function($query) {

    $query->term(['foo' => 'bar']);
    $query->term(['foo' => 'bar'], function($termQuery) {
        $termQuery->setTerm('baz', 'qux', 2.0);
    });

});
```

### Terms Query

[](#terms-query)

```
$laralastica->search('foo', function($query) {

    $query->terms('foo', ['bar', 'baz']);
    $query->terms('foo', ['bar', 'baz'], function($query) {
        $query->setMinimumMatch(5);
    });

});
```

### Wildcard Query

[](#wildcard-query)

```
$laralastica->search('foo', function($query) {

    $query->wildcard('foo', 'bar');

});
```

Filters
-------

[](#filters)

Occasionally you will want to run a query to exclude/include records, but you don't want the query to effect the score.

You can do this using filters.

To add a filter hit the `filter` methods and pass it a callback. The callback will be passed an instance of the laralastica builder as the first parameter.

For example if only wanted to search against records that had a due date we could do the following.

```
$laralastica->search('foo', function($query) {
    $query->matchAll()
          ->filter(function($query) {
            $query->exists('due_date');
          });
});
```

Paginate Results
----------------

[](#paginate-results)

To get a paginated list of results use the `paginate` method and pass the amount to paginate the results by.

```
$laralastica->paginate('foo', function($query) {

    $query->matchAll();

}, 15);
```

Raw Elastica Queries
--------------------

[](#raw-elastica-queries)

To run a raw elastica query create the query instance and then pass it to the `query` method.

```
$laralastica->search('foo', function($query) {

    $match = new \Elastica\Query\Match();

    $query->query($match);

});
```

The Result Collection
---------------------

[](#the-result-collection)

The search method will return an instance of the result collection. This extends the default laravel collection but also adds a couple of laralastica specific methods.

### Total Hits

[](#total-hits)

Gets the total amount of hits matched by the query.

```
$results = $laralastica->search('foo', function($query) { $query->matchAll() });

$results->totalHits();
```

### Maximum Score

[](#maximum-score)

Gets the maximum score matched by the search.

```
$results = $laralastica->search('foo', function($query) { $query->matchAll() });

$results->maxScore();
```

### Time Taken

[](#time-taken)

Gets the time taken to execute the elasticsearch query.

```
$results = $laralastica->search('foo', function($query) { $query->matchAll() });

$results->totalTime();
```

###  Health Score

35

—

LowBetter than 80% of packages

Maintenance12

Infrequent updates — may be unmaintained

Popularity27

Limited adoption so far

Community17

Small or concentrated contributor base

Maturity71

Established project with proven stability

 Bus Factor1

Top contributor holds 96.3% 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 ~34 days

Recently: every ~73 days

Total

51

Last Release

2274d ago

Major Versions

v2.4.2 → v3.0.02018-07-30

v1.4.1 → v2.4.42018-09-18

v2.4.4 → v3.0.32018-09-18

v2.4.5 → v3.1.02018-09-19

2.x-dev → v3.1.22019-05-07

PHP version history (3 changes)v0.1PHP &gt;=5.4.0

v2.0PHP &gt;=5.5.9

v3.0.0PHP ^7.0

### Community

Maintainers

![](https://www.gravatar.com/avatar/df807d0371b1b265ea1becedfa4001428f278e7632c6d175e2afb2921f5788a3?d=identicon)[michaeljennings](/maintainers/michaeljennings)

---

Top Contributors

[![michaeljennings](https://avatars.githubusercontent.com/u/5189701?v=4)](https://github.com/michaeljennings "michaeljennings (285 commits)")[![AmrSoliman](https://avatars.githubusercontent.com/u/3324468?v=4)](https://github.com/AmrSoliman "AmrSoliman (4 commits)")[![georgehanson](https://avatars.githubusercontent.com/u/23167178?v=4)](https://github.com/georgehanson "georgehanson (4 commits)")[![ceesvanegmond](https://avatars.githubusercontent.com/u/883497?v=4)](https://github.com/ceesvanegmond "ceesvanegmond (1 commits)")[![matthewbdaly](https://avatars.githubusercontent.com/u/450801?v=4)](https://github.com/matthewbdaly "matthewbdaly (1 commits)")[![threesquared](https://avatars.githubusercontent.com/u/892142?v=4)](https://github.com/threesquared "threesquared (1 commits)")

---

Tags

elasticsearch-querieslaravel-packagelaravelelasticsearchelastica

### Embed Badge

![Health badge](/badges/michaeljennings-laralastica/health.svg)

```
[![Health](https://phpackages.com/badges/michaeljennings-laralastica/health.svg)](https://phpackages.com/packages/michaeljennings-laralastica)
```

###  Alternatives

[laravel/scout

Laravel Scout provides a driver based solution to searching your Eloquent models.

1.7k49.4M479](/packages/laravel-scout)[laravel/pulse

Laravel Pulse is a real-time application performance monitoring tool and dashboard for your Laravel application.

1.7k12.1M99](/packages/laravel-pulse)[roots/acorn

Framework for Roots WordPress projects built with Laravel components.

9682.1M97](/packages/roots-acorn)[laravel/cashier

Laravel Cashier provides an expressive, fluent interface to Stripe's subscription billing services.

2.5k25.9M107](/packages/laravel-cashier)[studio/laravel-totem

A Laravel package to manage your cron jobs through a beautiful dashboard

1.8k1.1M](/packages/studio-laravel-totem)[flat3/lodata

OData v4.01 Producer for Laravel

96320.9k](/packages/flat3-lodata)

PHPackages © 2026

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