Client-side search
Client side search
Indexing operations aside, you should perform searches directly from your frontend, using JavaScript. This drastically improves search response times, and reduces the load and traffic on your servers.
Generate search keys
With client-side implementations, remember to use the search-only API keys. You should never share your admin API key with anyone, it must remain strictly confidential.
Scout Extended provides the searchKey
method to generate a search key for each searchable
class:
1
2
3
use Algolia\ScoutExtended\Facades\Algolia;
$searchKey = Algolia::searchKey(Article::class);
The $searchKey
this method returns restricts searches to the given Searchable
class, and no other Searchable
classes.
The searchKey
method uses the application cache to return the same search key until its expiry, 24 hours after generation.
Integration with Vue InstantSearch
Scout Extended doesn’t dictate which JavaScript solution to use. You’re free to pick your favorite InstantSearch flavor. The example below covers the Vue InstantSearch integration.
Installing Vue InstantSearch
Since Laravel ships with Vue by default, there’s nothing to set up. You only have to add vue-instantsearch
as a dependency with npm and register it as a Vue
plugin:
1
npm install vue-instantsearch algoliasearch
Then, open up your resources/js/app.js
and add the following lines just after the window.Vue = require('vue');
line:
1
2
3
4
import algoliasearch from 'algoliasearch/lite';
import InstantSearch from 'vue-instantsearch/vue3/es';
Vue.use(InstantSearch);
To compile the JavaScript into the app.js
bundle file while working on it, run:
$
npm run watch
Scaffolding a search interface
The following example shows a small search interface with a minimal design. Since the template needs access to the application ID and API key, you need to move the Vue initialization into a Blade template.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
<div id="app">
<!-- In a default Laravel app, Vue will render inside an #app div -->
<ais-instant-search
:search-client="searchClient"
index-name="{{ (new App\Article)->searchableAs() }}"
>
<ais-search-box placeholder="Search articles..."></ais-search-box>
<ais-hits>
<template v-slot:item="{ item }">
<div>
<h1>@{{ item.title }}</h1>
<h4>@{{ item.summary }}</h4>
</div>
</template>
</ais-hits>
</ais-instant-search>
</div>
<script>
new Vue({
data: function() {
return {
searchClient: algoliasearch(
'{{ config('scout.algolia.id') }}',
'{{ Algolia\ScoutExtended\Facades\Algolia::searchKey(App\Article::class) }}',
),
};
},
el: '#app',
});
</script>
You can refer to the Vue InstantSearch documentation to learn more about Vue InstantSearch and its components.
InstantSearch is also available for React and vanilla JavaScript.