Search code examples
laravelalgolialaravel-scout

Laravel switch to eloquent search if Scout and Algolia stopped


I am using Scout and Algolia for creating my search engine and using the community plan which is limited and free.

I am wondering is there a way to switch back to the normal eloquent using WHERE LIKE if a problem happened in Scout or Algolia like subscription?


Solution

  • You can decorate algolia engine with fallback decorator and switch to fallback if an error occurs.

    class AppServiceProvider extends ServiceProvider
    {
        /**
         * {@inheritdoc}
         */
        public function boot(): void
        {
    
            resolve(EngineManager::class)->extend(AppSearchEngine::class, function () {
                $origin = new AlgoliaEngine();
                $fallback = new MySQLEngine();
                return new FallbackEngine($origin, $fallback);
            });
        }
    }
    
    class FallbackEngine extends Engine {
    ...
        public function search(Builder $builder)
        {
            try {
                return $this->origin->search();
            } ($e \Excheption) {
                return $this->fallback->search();
            }
        }
    ...
    }