Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
L

laravel-scout-elasticsearch

> 后端框架
Open source

Search among multiple models with ElasticSearch and Laravel Scout

743 stars0 likes2 views
WebsiteGitHub

About

Search among multiple models with ElasticSearch and Laravel Scout

Stay with Ukraine

UNITED24 launches the first fundraiser towards terrestrial robotic platforms. Squads of robots will save the lives of our military and civilians. They will become logistics devices, tow trucks, minelayers and deminers, as well as self-destructive robots. They will fight alongside people and for people.

The first robots are already proving their effectiveness on the battlefield. There will be more of them soon. Many more.

For Laravel Framework = 8.0

  • Laravel Framework version >= 8.0.0
Elasticsearch version ElasticsearchDSL version
>= 8.0 >= 8.0.0
>= 7.0 >= 3.0.0
>= 6.0, [
// Other Service Providers

\Matchish\ScoutElasticSearch\ElasticSearchServiceProvider::class

],

Set `ELASTICSEARCH_HOST` env variable

ELASTICSEARCH_HOST=host:port

or use commas as separator for additional nodes

ELASTICSEARCH_HOST=host:port,host:port


You can disable SSL verification by setting the following in your env

ELASTICSEARCH_SSL_VERIFICATION=false

…

php use Matchish\ScoutElasticSearch\Searchable\ImportSourceFactory; ... public function register(): void { $this->app->bind(ImportSourceFactory::class, MyImportSourceFactory::class);

Here is an example of `MyImportSourceFactory`
```php
namespace Matchish\ScoutElasticSearch\Searchable;

final class MyImportSourceFactory implements ImportSourceFactory
{
    public static function from(string $className): ImportSource
    {
        //Add all required scopes
        return new DefaultImportSource($className, [new WithCommentsScope()]);
    }
}

class WithCommentsScope implements Scope {

    /**
     * Apply the scope to a given Eloquent query builder.
     *
     * @param \Illuminate\Database\Eloquent\Builder $builder
     * @param \Illuminate\Database\Eloquent\Model $model
     * @return void
     */
    public function apply(Builder $builder, Model $model)
    {
        $builder->with('comments');
    }
}

You can also customize your indexed data when you save models by leveraging the toSearchableArray method provided by Laravel Scout through the Searchable trait

Example:

php
class Product extends Model 
{
    use Searchable;

    /**
     * Get the indexable data array for the model.
     *
     * @return array
     */
    public function toSearchableArray()
    {
        $with = [
            'categories',
        ];

        $this->loadMissing($with);

        return $this->toArray();
    }
}

…

php
Product::search('(title:this OR description:this) AND (title:that OR description:that)')

If it's not enough in your case you can pass a callback to the query builder

php
$results = Product::search('zonga', function(\Elastic\Elasticsearch\Client $client, $body) {

    $minPriceAggregation = new MinAggregation('min_price');
    $minPriceAggregation->setField('price');
    
    $maxPriceAggregation = new MaxAggregation('max_price');
    $maxPriceAggregation->setField('price');
    
    $brandTermAggregation = new TermsAggregation('brand');
    $brandTermAggregation->setField('brand');

    $body->addAggregation($minPriceAggregation);
    $body->addAggregation($brandTermAggregation);
    
    return $client->search(['index' => 'products', 'body' => $body->toArray()])->asArray();
})->raw();

…

php
Product::search('(title:this OR description:this) AND (title:that OR description:that)')
    ->where('price', 100)
    ->whereIn('type', ['used', 'like new'])
    ->whereNotIn('type', ['new', 'refurbished']);

Scout does not support any operators, but you can pass ElasticSearch terms like RangeQuery as value to ->where():

php

use ONGR\ElasticsearchDSL\Query\TermLevel\RangeQuery;

Product::search('(title:this OR description:this) AND (title:that OR description:that)')
    ->where('price', new RangeQuery('price', [
        RangeQuery::GTE => 100,
        RangeQuery::LTE => 1000,
    ]);

And if you just want to search using RangeQuery without any query_string, you can call the search() method directly and leave the param empty.

php

use ONGR\ElasticsearchDSL\Query\TermLevel\RangeQuery;

Product::search()
    ->where('price', new RangeQuery('price', [
        RangeQuery::GTE => 100,
    ]);

…

php
Product::search()
    ->take(20)
    ->options([
        'from' => 20,
    ])
    ->paginate(50);

This will return the first 50 results, ignoring the specified offset.

Search amongst multiple models

You can do it with MixedSearch class, just pass indices names separated by commas to the within method.

php
MixedSearch::search('title:Barcelona or to:Barcelona')
    ->within(implode(',', [
        (new Ticket())->searchableAs(),
        (new Book())->searchableAs(),
    ]))
    ->get();

In this example you will get collection of Ticket and Book models where ticket's arrival city or book title is Barcelona

Working with results

Often your response isn't collection of models but aggregations or models with higlights and so on. In this case you need to implement your own implementation of HitsIteratorAggregate and bind it in your service provider

Here is a case

:free: License

Scout ElasticSearch is an open-sourced software licensed under the MIT license.

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

PHPelasticsearchlaravellaravel-scoutscout

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category后端框架
PricingOpen source

> Related tools

N
Node.js
基于 V8 的 JavaScript 运行时
D
Django
Python 高级 Web 框架
S
Spring Boot
Java 生态主流微服务框架