Integrations / Frameworks / Laravel / Import Into Algolia

Import Into Algolia

Import

When setting up Scout Extended, you probably have existing data that you would like to import. There is an scout:import Artisan command to import data:

$
php artisan scout:import

The searchable classes are automatically detected, but feel free to specify the searchable class to import:

$
php artisan scout:import "App\Article"

Need to import data in production? Take a look at the section Zero Downtime Reimports.

Flushing and clearing

The scout:flush Artisan command is the easiest way to flush the data from Algolia’s index:

$
php artisan scout:flush

Keep data in sync

Every time you save or update a model, Laravel emits an event. Scout listens for those events, informing your app to make an HTTP call to Algolia to update its index.

You don’t have to do anything else, you can use your searchable class as usual. For example, in a controller you may have:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class ArticleController extends Controller
{
    /**
     * Update the given article.
     *
     * @param  Request  $request
     * @param  string  $id
     * @return Response
     */
    public function update(Request $request, $id)
    {
        Article::find(request('id'));

        $article->title = request('title');

        /**
         *  Scout will automatically persist the
         *  changes to your Algolia search index.
         */
        $article->update();
    }
}

It’s important to note that the data isn’t synced when using mass assignment methods, since the saved and updated events aren’t dispatched in that case:

1
2
3
4
5
6
/**
 *  Here, Scout will NOT persist the
 *  changes to your Algolia search index.
 */
Article::where('id', request('id'))
    ->update(['title' => request('title')]);

Conditional model sync

Sometimes you may want to sync a searchable class just when something else is true. To do this, you can define a shouldBeSearchable method on your searchable class. Scout Extended syncs your model if this method returns true.

1
2
3
4
5
6
7
8
9
class Article extends Model
{
    use Searchable;
    
    public function shouldBeSearchable()
    {
        return $this->isPublished();
    }
}

Pause indexing

Scout documentation shows a nice way to change a searchable model without triggering indexing calls using a callback.

There is also a static method you can use to turn off syncing. This is useful if you’re performing lots of SQL queries to change content. Once complete, you can sync the changes manually.

For example, in your DatabaseSeeder class:

1
2
3
4
5
6
7
8
9
10
11
12
13
class DatabaseSeeder extends Seeder
{
    public function run()
    {
        Article::disableSearchSyncing();

        $this->call(ArticleSeeder::class);

        Article::all()->searchable();

        Article::enableSearchSyncing();
    }
}

Did you find this page helpful?