Integrations / Frameworks / Laravel / Server Side Search
Apr. 30, 2019

Server Side Search

Searching

You may begin searching in a searchable class using the search method. The search method accepts a single string that will be used to search in your searchable class index:

1
$articles = Article::search('Star Trek')->get();

You can also paginate the search query and work with Soft Deleted models. Head over to Laravel Documentation to find more.

where

The where method may be used to compare a field’s value against another value. With Scout Extended, this method shares the same API of the Laravel Query Builder. Allowing you to filter results either via a comparison or a range numerically:

1
2
3
$articles = Article::search('Star Trek')->where('views', '>', 100)->get();
$articles = Article::search('Star Trek')->where('created_at', '>=', now()->subDays(7))->get();
$articles = Article::search('Star Trek')->where('views', 100)->get(); // views = 100

The supported operators are: <, <=, =, !=, >=, >.

whereBetween

The whereBetween method verifies that a field’s value is between two values:

1
2
3
$products = Products::search('Star Trek')
    ->whereBetween('price', [100, 200])
    ->get();

whereIn

The whereIn method verifies that a field’s value is contained within the given array:

1
2
3
$products = Products::search('Star Trek')
    ->whereIn('id', [1, 2])
    ->get();

count

The count method returns the number of hits matched by the query:

1
$count = Article::search('Star Trek')->count();

aroundLatLng

The aroundLatLng method will add geolocation parameter to the search request. You can define a point with its coordinates. This method is pure syntactic sugar, and you can use the method with to specify more location details such us aroundRadius or aroundLatLngViaIP.

1
2
3
$articles = Article::search('query')
    ->aroundLatLng(48.8588536, 2.3125377)
    ->get();

with

The with method gives you complete access to customize search API parameters.

1
2
3
4
5
6
$articles = Article::search('Star Trek')
    ->with([
        'hitsPerPage' => 30,
        'filters' => 'attribute:value',
        'typoTolerance' => false,
    ])->get();

Results Metadata

In addition to the retrieved models, when using the scoutMetaData method, you get an array with information about the hits.

The key _highlightResult contains all the attributes that may be highlighted (by default, all the searchable attributes):

1
2
$metadata = Article::search('Star Trek')->get()->first()->scoutMetaData();
$highlightResult = $metadata['_highlightResult'];

The key _rankingInfo contains detailed ranking information. This setting lets you see exactly which ranking criteria played a role in selecting each model:

1
2
$metadata = Article::search('Star Trek')->get()->first()->scoutMetaData();
$rankingInfo = $metadata['_rankingInfo'];

Did you find this page helpful?