How to use elasticsearch from scratch in laravel?

Share Me
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  

Today now in this post i will show you How to use elasticsearch from scratch in laravel. When we are working on any large data website on laravel, then we need to apply the search engine for our website. When I was working on elasticsearch for search engine then i was face some problems. Because i had no experience on elasticsearch. So at first I need to learn this from starting but i was found that how to install elasticsearch and use in laravel application.

So now, in this example i will give you a full example the from scratch, after this example you use this on you own project

Step 1: Install Elasticsearch

At first step we need to install elasticsearch in our local machine. If we haven’t installed this before then we can install this from here: ElasticSearch Docs.

If we are working on ubuntu system then we can learn easily how install from here : How to config Elastic search in our local system

Step 2: Package Installation

Now in this step we need to install elasticquent/Elasticquent package for use the elasticsearch api. So at first need to fire the bellow line add in your composer.json file and then update your composer:

"elasticquent/elasticquent": "dev-master"

After the install elasticquent/elasticquent package, then we need to add the provider path and alias path in our config/app.php file so need to open that file and add the bellow code.

config/app.php

return [
	......
	'provides' => [
		......
		......,
		Elasticquent\ElasticquentServiceProvider::class,
	],
	'aliases' => [
		......
		......,
		'Es' => Elasticquent\ElasticquentElasticsearchFacade::class,
	],
]

So now then we need to generate the configuration file for the elastichsearch. Now need to fire bellow command in our terminal:

php artisan vendor:publish --provider="Elasticquent\ElasticquentServiceProvider"
Step 3: Create items table and model

Now in this step we need to create the migration for items table by using Laravel php artisan command. So now fire the bellow command:

php artisan make:model Item -m

Now after this command we will find one file in following the path database/migrations and then we have to put the bellow code in our migration file for create items table.

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


class CreateItemsTable extends Migration
{

    public function up()
    {
        Schema::create('items', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title');
            $table->text('description');
            $table->timestamps();
        });
    }
    public function down()
    {
        Schema::drop("items");
    }
}

and it also create Item model for items table, this file we found in this path app/Models/Item.php and put bellow content in item.php file:

app/Models/Item.php

namespace App;

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


class Item extends Model
{
    use ElasticquentTrait;
    public $fillable = ['title','description'];
}
Step 4: Route and Controller

Now in this step we need to add the some route in our route file. So just copy the bellow route and put in your file.

app/Http/routes.php

Route::get('ItemSearch', 'ItemSearchController@index');
Route::post('ItemSearchCreate', 'ItemSearchController@create');

Ok, now we need to create a new controller as name ItemSearchController in this path app/Http/Controllers/ItemSearchController.php.

This controller will manage the all search from the elastichsearch and add to index function:

app/Http/Controllers/ItemSearchController.php

namespace App\Http\Controllers;


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


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


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


        $item = Item::create($request->all());
        $item->addToIndex();
        return redirect()->back();
    }
}
Step 5: Create View

Now we are in last step and we have to create a blade file as name ItemSearch.blade.php file for manage the listing on search function. So just need to copy and paste this file :

ItemSearch.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 Search Using Elasticsearch</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($items))
			    		@foreach($items as $key => $value)
			    			<h3 class="text-danger">{{ $value['title'] }}</h3>
			    			<p>{{ $value['description'] }}</p>
			    		@endforeach
			    	@endif
		  		</div>
		  		<div class="col-lg-6">
		  			<div class="panel panel-default">
	  					<div class="panel-heading">
	  						Create New Items
	  					</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' => 'ItemSearchCreate','autocomplete'=>'off')) !!}
	  							<div class="row">
			                        <div class="col-xs-12 col-sm-12 col-md-12">
			                            <div class="form-group">
			                                <strong>Title:</strong>
			                                {!! Form::text('title', null, array('placeholder' => 'Title','class' => 'form-control')) !!}
			                            </div>
			                        </div>
			                        <div class="col-xs-12 col-sm-12 col-md-12">
			                            <div class="form-group">
			                                <strong>Description:</strong>
			                                {!! Form::textarea('description', null, array('placeholder' => 'Description','class' => 'form-control','style'=>'height:100px')) !!}
			                            </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

Read Also :Laravel Join with Subquery in Query Builder Example

Thanks for read. I hope it help you. For more you can follow us on facebook.

About Shahriar Sagor

My name is Shahriar sagor. I'm a developer. I live in Bangladesh and I love to write tutorials and tips that will help to other Developer's. I am a big fan of PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.

View all posts by Shahriar Sagor →