How to Setup Elasticsearch with Laravel 5

Elasticsearch is a server based tool that is capable of full-text searching at very high speed. It is powered by Apache Lucene (which is an open source full text search library). It is able to achieve this speed because instead of searching the whole word matching the desired result from the whole database, it uses indexing.

This is similar to the indexing of a book. In this case, indexes are made out of letters. So as soon as you start searching, the Elasticsearch mechanism starts hovering to your result matching your first letter entries.

How Do I Set It Up?

We will learn in this little tutorial about how we can setup Elasticsearch with our Laravel App. We will see some basic examples and will start working with them. I would love it if you follow the guide side by side so you can make changes accordingly for better learning.

Prerequisites

  • You have an activated server on Cloudways. Click here to launch one.
  • You have an active Laravel App installed on your server.
  • You have installed Elasticsearch on your Cloudways Server. If not click here to see the related guide.

Step 1: Checking Elasticsearch Installation

Open up SSH terminal and enter the following command:

$ curl -XGET 127.0.0.1:9200

Step 2: Installing Elasticsearch Client for PHP Laravel

$ composer require elasticsearch/elasticsearch

Step 3: Checking Elasticsearch

Let’s make some changes in our routes.php and see if we can check our client installation.

$ vim /public_html/app/Http/routes.php

Now edit a route:

Route::get('/', function () { $client = Elasticsearch\ClientBuilder::create()->build(); var_dump($client); });

Now browse your app and you will get something like this:

object(Elasticsearch\Client)[163] public 'transport' => object(Elasticsearch\Transport)[161] public 'connectionPool' => object(Elasticsearch\ConnectionPool\StaticNoPingConnectionPool)[160] private 'pingTimeout' => int 60 private 'maxPingTimeout' => int 3600 protected 'connections' => array (size=1) ... protected 'seedConnections' => array (size=1) ... protected 'selector' => object(Elasticsearch\ConnectionPool\Selectors\RoundRobinSelector)[157] ... protected 'connectionFactory' => object(Elasticsearch\Connections\ConnectionFactory)[156] ... public 'connectionPoolParams' => array (size=1)

Now let’s see how can we inject into our Elasticsearch:


Originally published at www.laravelfeed.com.

Like what you read? Give LaravelFeed a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.