> ## Documentation Index
> Fetch the complete documentation index at: https://algolia.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Get started with Laravel Scout and Vue InstantSearch

> Automatically index your data with Scout and use Vue.js to build instant result pages.

<Note>
  This tutorial was written for Laravel 8.
  It doesn't work with newer versions of Laravel.
</Note>

While Scout seamlessly wraps the Algolia engine,
the Vue.js bundle simplifies the use of Algolia's InstantSearch library.

For this tutorial, you need a fresh Laravel application.
You'll index a `Contact` model, which holds a name, an email, a company, and a state.

The tutorial consists of 4 steps:

1. Create the model class and seed the database
2. Install Scout, then index your data
3. Install Vue InstantSearch
4. Build your search experience

## Create the model

Create an empty model and a migration file with the corresponding `artisan` command.

```sh Command line icon=square-terminal theme={"system"}
php artisan make:model -m Contact
```

This creates a model class in `app/Contact.php` and a migration in `database/migrations/DATE_create_contacts_table.php`.

Edit this migration file so it looks like this:

```php PHP icon=code theme={"system"}
<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateContactsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('contacts', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('email');
            $table->string('company')->nullable();
            $table->string('state')->nullable();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('contacts');
    }
}
```

Now that your Laravel app knows what a contact is,
you can migrate the database to reflect these changes.

```sh Command line icon=square-terminal theme={"system"}
php artisan migrate
```

### Import your fake data

Now you need to import data from [Algolia's contacts dataset](https://raw.githubusercontent.com/algolia/datasets/master/contacts/contacts.json) and place it at the root of your `resources` folder.

Create a seeder class so that you can select what data to import.

```sh Command line icon=square-terminal theme={"system"}
php artisan make:seeder ContactSeeder
```

Laravel generated a new `database/seeders/ContactSeeder.php` file. Open it up and edit it to add the following class.

```php PHP icon=code theme={"system"}
<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;

class ContactSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $contacts = [];

        $raw = json_decode(
            file_get_contents(resource_path('contacts.json')),
            true
        );

        foreach ($raw as $contact) {
            $contacts[] = [
                'name' => $contact['firstname'].' '.$contact['lastname'],
                'email' => $contact['email'],
                'company' => $contact['company'],
                'state' => $contact['state'],
            ];
        }

        DB::table('contacts')->insert($contacts);
    }
}
```

This class opens the JSON dataset and pushes what you need into the database.
You can now seed your database:

```php PHP icon=code theme={"system"}
php artisan db:seed --class=ContactSeeder
```

## Install Laravel Scout

Install Laravel Scout and Algolia's API client using composer.

```sh Command line icon=square-terminal theme={"system"}
composer require laravel/scout
composer require algolia/algoliasearch-client-php:^2.2
```

If you use a Laravel version older than 5.5,
add the service provider class name to the `providers` array in the `config/app.php` file.
If you use Laravel 5.5 and later, you can skip this step.

```php PHP icon=code theme={"system"}
Laravel\Scout\ScoutServiceProvider::class,
```

Create a `scout.php` file in your `config` folder with the following command:

```sh Command line icon=square-terminal theme={"system"}
php artisan vendor:publish --provider="Laravel\Scout\ScoutServiceProvider"
```

### Configure Algolia's credentials

Go to the Algolia dashboard, to the [API keys](https://dashboard.algolia.com/account/api-keys/) section.
You can find three important credentials there:

* Your application ID
* Your search-only API key
* Your admin API key

You need to put these in your `.env` file.
**Don't** put these credentials directly in your `config/scout.php` file,
they shouldn't be part of your version history.

```dotenv .env icon=lock-keyhole theme={"system"}
ALGOLIA_APP_ID=# Your Algolia application ID
ALGOLIA_SECRET=# Your Algolia write API key
MIX_ALGOLIA_APP_ID=# Your Algolia application ID
MIX_ALGOLIA_SEARCH=# Your Search API key
```

## Index your data

Laravel Scout provides a convenient way to index your data:
all you need to do is add a trait to your model.
This trait adds functionalities to the default `Model` class,
including keeping your data in sync with Algolia.

Open up your `app/Contact.php` file and add the `Laravel/Scout/Searchable` trait.

```php PHP icon=code theme={"system"}
<?php
namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Laravel\Scout\Searchable;

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

Before you can keep your data in sync, you need to perform a batch import the first time.
Scout has added a command for this.

```sh Command line icon=square-terminal theme={"system"}
php artisan scout:import 'App\Contact'
```

Take a look at your dashboard and you should be able to see your data.

## Setup Vue.js

You should use [frontend search](https://support.algolia.com/hc/en-us/articles/4406981933457-Searching-from-the-frontend-or-the-back-end-What-do-you-recommend-), which gives your users instant results, and also frees up your server from processing every search request.
You can use [Vue InstantSearch](/doc/guides/building-search-ui/what-is-instantsearch/vue)
to create a frontend search without writing a lot of custom JavaScript code to handle complex search behaviors.

### Install Vue InstantSearch

Since Laravel ships with Vue by default,
you have nothing to setup.
You'll only need to add `vue-instantsearch` as a dependency with npm and register it as a Vue plugin.

```sh Command line icon=square-terminal theme={"system"}
npm install vue-instantsearch algoliasearch instantsearch.css
```

Then, open up your `resources/js/app.js` and add the following line just after the `window.Vue = require('vue');` line.

<CodeGroup>
  ```js Vue3 icon=code theme={"system"}
  import VueInstantSearch from "vue-instantsearch/vue3/es";

  Vue.use(VueInstantSearch);
  ```

  ```js Vue2 icon=code theme={"system"}
  import VueInstantSearch from "vue-instantsearch";

  Vue.use(VueInstantSearch);
  ```
</CodeGroup>

## Build your search experience

### Compile JavaScript code

To compile the JavaScript into the `app.js` bundle file,
run the following command:

```sh Command line icon=square-terminal theme={"system"}
npm run watch
```

This rebuilds your assets every time you change one of the JavaScript files.

### Defining where Vue renders

In a default Laravel app,
Vue renders inside an `#app` tag.

```html HTML icon=code-xml theme={"system"}
<div id="app"></div>
```

Create a new file in your `components` directory called `MySearch.vue` and register it in `app.js` for the search interface:

```js JavaScript icon=code theme={"system"}
Vue.component("my-search", require("./components/MySearch.vue").default);
```

Then update the blade view, adding the `my-search` component:

```php PHP icon=code theme={"system"}
<div id="app">
    <my-search />
</div>
<script src="{{ mix('js/app.js') }}"></script>
```

<Info>You can use [`vue-devtools`](https://github.com/vuejs/vue-devtools) to debug your Vue components.</Info>

To use InstantSearch's default theming, import it in `scss/app.scss`.

```css CSS icon=paintbrush theme={"system"}
@import "~instantsearch.css/themes/algolia-min";
```

### InstantSearch components

Every InstantSearch component needs to be inside an `<ais-instant-search>` tag.
This lets the library know how to contact Algolia servers.
You can set this up in `MySearch.vue`.

```vue-html Vue icon=code theme={"system"}
<template>
  <ais-instant-search :search-client="searchClient" index-name="contacts">
    <!-- Other search components go here -->
  </ais-instant-search>
</template>

<script>
import algoliasearch from 'algoliasearch/lite'

export default {
  data() {
    return {
      searchClient: algoliasearch(
        process.env.MIX_ALGOLIA_APPLICATION_ID,
        process.env.MIX_ALGOLIA_SEARCH_API_KEY
      ),
    }
  },
}
</script>
```

The library provides ready-to-use components to add a search box and display the results.

```vue-html Vue icon=code theme={"system"}
<ais-instant-search :search-client="searchClient" index-name="contacts">
  <ais-search-box placeholder="Search contacts..."></ais-search-box>
  <ais-hits></ais-hits>
</ais-instant-search>
```

By default, the component just shows the ID of the results.
You can pass a template to change how your results display.

```vue-html Vue icon=code theme={"system"}
<ais-hits>
  <template v-slot:item="{ item }">
    <h1>
      <ais-highlight
        :hit="item"
        attribute="name"
      />
    </h1>
    <h4>
      <ais-highlight
        :hit="item"
        attribute="company"
      /> -
      <ais-highlight
        :hit="item"
        attribute="state"
      />
    </h4>

    <ul>
      <li>{{ item.email }}</li>
    </ul>

  </template>
</ais-hits>
```

## See also

* [The Scout Extended documentation](/doc/framework-integration/laravel/getting-started/introduction-to-scout-extended)
* [The Laravel Scout documentation](https://laravel.com/docs/scout)
* [Vue InstantSearch documentation](/doc/guides/building-search-ui/what-is-instantsearch/vue)
