A Blog Of Random Coding Techniques & Experiments Robert Askam

Full Text Search with Laravel Scout and Algolia and Vue.js Post Full Text Search with Laravel Scout and Algolia and Vue.js 1 year ago

Here we will use Laravel Scout and Algolia to add the instant full text search to your Laravel site.

Prerequisites

In you composer.json file add:
"laravel/scout" : "2.0.2",
"algolia/algoliasearch-client-php" : "1.13.0",

Run in your terminal:
$composer update

Laravel Scout

Next, you should add the ScoutServiceProvider to the providers array of your config/app.php configuration file.
Laravel\Scout\ScoutServiceProvider::class,
Open your .env file and add the following lines:
ALGOLIA_APP_ID
ALGOLIA_SECRET

Algolia

Sign up for free and go to your dashboard from the menu. In the left column click on API Key.
Copy your Application ID into ALGOLIA_APP_ID in .env and copy the Admin API Key into your ALGOLIA_SECRET.

Laravel

In your Model, for example lets use posts add a searchable Trait as provided by Scout, your Model should look like this.
namespace App;
use Laravel\Scout\Searchable;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
use Searchable;
}
If you have existing records in your Model then you need to run this to send them to Algolia.
php artisan scout:import "App\Post"
You should now be able to see them in the Algolia Index Section.

Vue Js

In your Vue Component within the script tags you should make it look like this to search, remember to change the fields ALGOLIA_APP_ID and ALGOLIA_SECRET with whats in your .env. The Var index is the name of the model you are searching.
var algoliasearch = require('algoliasearch');
var client = algoliasearch('ALGOLIA_APP_ID', 'ALGOLIA_SECRET');
var index = client.initIndex('posts');
export default {
mounted() {

},
data() {
return {
search: [],
q: ''
}
},

methods: {
searchIndex() {
index.search(this.q, (err, content) =>{
this.search = content.hits;
})
}
}
}
Now in the HTML simply add:
v-for="post in search"