Laravel Elastic search integration from scratch with example

By | December 13, 2018
Laravel Elastic search integration from scratch with example

When we are building a large or medium level applications we generally want to create a search module and today’s time we all want to get fast searching results with auto suggest. And this can be very fast with elastic search. In this article i will let you know laravel elastic search integration from scratch with example.

Elastic search integration in laravel is very easy. And i am sure you all can integrate this into your laravel application by following the all the steps here.

So without wasting our time let’s start integration process. In this article i will use elasticquent/elasticquent package.

Step1: Install Elastic search

In the first step you will need to install elastic search on your machine where you want to develop your application. You can download from here.

You can follow the easy docs provided by elastic search to install into your application. You can follow this link

Step2: Install package

After installing elastic search in your system. You will need to start integration process in laravel application. And in this step you will need to execute following command to install  elasticquent/elasticquent package.

"elasticquent/elasticquent": "dev-master"

Above command will download the package in your laravel application.

Now set configuration by adding provider and alias name in config/app.php file. Add the following lines into config/app.php file.

config/app.php

return [

  ......

  'provides' => [

    ......

    ......,

    Elasticquent\ElasticquentServiceProvider::class,

  ],

  'aliases' => [

    ......

    ......,

    'Es' => Elasticquent\ElasticquentElasticsearchFacade::class,

  ],

]

Now the package has been downloaded and provided added. and now you will need to generate configuration file fole elastic search with the following command.

php artisan vendor:publish --provider="Elasticquent\ElasticquentServiceProvider"

Step3: Create table and model

In this step we will create a customers table and Customer model for database records.

You can create a table with necessary fields directly from your database. But here i will create a migration and will write columns to generate a table.

So for that migration run the artisan command into your terminal.

php artisan make:migration create_customers_table

Now migration file for customer table has been generated and you will need to open this file available at database/migrations path and put the following lines of code.

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


class CreateItemsTable extends Migration
{


    public function up()
    {
        Schema::create('customers', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('email');
            $table->string('phone');
            $table->timestamps();
        });
    }


    public function down()
    {
        Schema::drop("customers");
    }
}

You migration has successfully done for customers table. now you will need to create a model for this customers table.

You can use the following command to create a model.

php artisan make:model Customer

After executing the above command in your terminal Customer.php file would be created in app directory.

Add elastic search into this model with the following code. Your customer model file will look like the below

namespace App;


use Illuminate\Database\Eloquent\Model;
use Elasticquent\ElasticquentTrait;


class Customer extends Model
{
    use ElasticquentTrait;


    public $fillable = ['name','email','phone'];


}

Step4: Add Routes

In this step we will need to add the required routes in routes/web.php file.

Route::get('CustomerSearch', 'CustomerSearchController@index');
Route::post('CustomerSearchCreate', 'CustomerSearchController@create');

Step5: Create controller and add methods

In this step we will create CustomerSearchController.php file into controllers directory. and add the following lined of code into this controller file.

app/Http/Controllers/CustomerSearchController.php

namespace App\Http\Controllers;


use Illuminate\Http\Request;
use App\Http\Requests;
use App\Item;


class CustomerSearchController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
    	if($request->has('search')){
    		$customers= Customer::search($request->input('search'))->toArray();
    	}
        return view('customer-search',compact('customers'));
    }


    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create(Request $request)
    {
    	$this->validate($request, [
      	'name' => 'required',
               'email' => 'required',
               'phone' => 'required',
        ]);


        $customer= Customer::create($request->all());
        $customer->addToIndex();


        return redirect()->back();
    }
}

Step6: Create required view

Now in this last step we will need to create a view to display the search result. So simply create a customer-search.blade.php view file in views directory. And add the code below.

customer-search.blade.php

@extends('layouts.app')


@section('content')
<div class="row">
    <div class="col-md-8 col-md-offset-2">
        <h1 class="text-primary" style="text-align: center;">Laravel 5 Elasticsearch search example</h1>
    </div>
</div>


<div class="container">
  <div class="panel panel-primary">
    <div class="panel-heading">
    	<div class="row">
      <div class="col-lg-6">
        {!! Form::open(array('method'=>'get','class'=>'')) !!}
        <div class="input-group">


          <input name="search" value="{{ old('search') }}" type="text" class="form-control" placeholder="Search for...">
          <span class="input-group-btn">
            <button class="btn btn-default" type="submit">Go!</button>
          </span>


        </div><!-- /input-group -->
        {!! Form::close() !!}
      </div><!-- /.col-lg-6 -->
    </div><!-- /.row -->
    </div>
    <div class="panel-body">

      	
      	<div class="row">
      		<div class="col-lg-6">
          	@if(!empty($customers))
          		@foreach($customers as $key => $value)
          			<h3 class="text-danger">{{ $value['name'] }}</h3>
          			<p>{{ $value['email'] }}</p>
                                                <p>{{ $value['phone'] }}</p>
          		@endforeach
          	@endif
      		</div>
      		<div class="col-lg-6">
      			<div class="panel panel-default">
    					<div class="panel-heading">
    						Create New Customer
    					</div>
    					<div class="panel-body">


    						@if (count($errors) > 0)
                <div class="alert alert-danger">
                  <strong>Whoops!</strong> There were some problems with your input.<br><br>
                  <ul>
                    @foreach ($errors->all() as $error)
                      <li>{{ $error }}</li>
                    @endforeach
                  </ul>
                </div>
              @endif


    						{!! Form::open(array('url' => 'CustomerSearchCreate','autocomplete'=>'off')) !!}
    							<div class="row">
                              <div class="col-xs-12 col-sm-12 col-md-12">
                                  <div class="form-group">
                                      <strong>Name:</strong>
                                      {!! Form::text('name', null, array('placeholder' => 'Name','class' => 'form-control')) !!}
                                  </div>
                              </div>
                              <div class="col-xs-12 col-sm-12 col-md-12">
                                  <div class="form-group">
                                      <strong>Email:</strong>
                                      {!! Form::text('email', null, array('placeholder' => 'Email','class' => 'form-control')) !!}
                                  </div>
                              </div>
                                                <div class="col-xs-12 col-sm-12 col-md-12">
                                  <div class="form-group">
                                      <strong>Phone:</strong>
                                      {!! Form::text('phone', null, array('placeholder' => 'Phone','class' => 'form-control')) !!}
                                  </div>
                              </div>
                          </div>


                          <div class="text-center">
                          	<button type="submit" class="btn btn-primary">Submit</button>
                          </div>


    						{!! Form::close() !!}


    					</div>
    				</div>
      		</div>
      	</div>


    </div>
  </div>
</div>
@endsection