Paulund
2017-12-30 #laravel

Laravel Command To Import Into Algolia

In the previous article we investigated how you can use Algolia with Laravel to create a realtime search. In this tutorial we learnt about the Laravel Scout command of import that allows you to import an entire Model data into the Algolia index.


php artisan scout:import 'App\Models\Post'

But there is a problem with this approach as it will just grab all the data for this model and import it into Algolia. As you can see we're doing this import on a Post model so we can assume that it's going to be used in a blog instance. In a blog post scenario you're most likely going to have different post statuses such as published, draft, scheduled etc. Therefore if we use the command above we will import posts which are drafts or scheduled posts. If you're going to use the Algolia search for the end user to search through posts the results are going to include draft posts in the results. This is the reason why we need to create our own command that we can use to import posts by performing a custom query and then index the results of the query. If you look at the Laravel scout documentation there is a section talking about how to batch import data. The package adds a searchable() method to query collection. This method will chunk the results and import them into Algolia.

Create A New Command

First we need to create a new command to do this we can use the artisan command php artisan make:command. This command will create a new file in App\Console\Commands. In the handle method we need to use the Post model and filter where the status is published and then method to import these into algolia.


namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\Post;

class ImportPostsAlgolia extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'blog:import-posts-algolia';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Import only the published posts into algolia';

    /**
     * Add all published posts to algolia
     */
    public function handle()
    {
        $this->info('Importing posts');
        Post::where('status', 'published')->searchable();
        $this->info('Posts imported');
    }
}