How to Use Elasticsearch from Scratch in Laravel?

By Hardik Savani November 5, 2023 Category : Laravel Elasticsearch

When i was working on my ecommerce website on laravel, i was need to apply search engine for my website. I was confused and thinking what i have to use, but my senior suggested to me elasticsearch for search engine. But i had no experience elasticsearch. I need to learn from starting but i found how to install elasticsearch and use in our laravel application.

Why we choose elasticsearch for search engine because elasticsearch provides a distributed, multitenant-capable full-text search engine with an HTTP web interface and JSON documents. So, in this example i going to give you full example from scratch, after this example you can find bellow preview.

Preview

Step 1: Install Elasticsearch

in first step you should install elasticsearch in your local machine. If you haven't installed then you can install from here: ElasticSearch Docs.

If you are working on ubuntu system then you can install easily from here : How to confige Elasticsearch in our local system.

Step 2: Package Installation

In this step we will install elasticquent/Elasticquent package for use elasticsearch api. so first fire bellow line add in your composer.json file and then update composer:

"elasticquent/elasticquent": "dev-master"

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

config/app.php

return [

......

'provides' => [

......

......,

Elasticquent\ElasticquentServiceProvider::class,

],

'aliases' => [

......

......,

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

],

]

Now we need to generate configration file for elastichsearch so fire bellow command in your terminal:

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

Step 3: Create items table and model

In this step we have to create migration for items table using Laravel 5 php artisan command, so first fire bellow command:

php artisan make:migration create_items_table

After this command you will find one file in following path database/migrations and you have to put bellow code in your 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");

}

}

After craete "items" table you should craete Item model for items, so first create file in this path app/Item.php and put bellow content in item.php file:

app/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

In this step you have to add some route in your route file. so first copy bellow route and put in your file.

app/Http/routes.php

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

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

Ok, now we should create new controller as ItemSearchController in this path app/Http/Controllers/ItemSearchController.php. this controller will manage all search from elastichsearch and add to index:

app/Http/Controllers/ItemSearchController.php

namespace App\Http\Controllers;


use Illuminate\Http\Request;

use App\Http\Requests;

use App\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

This is a last step and you have to create ItemSearch.blade.php file for manage listing on search function so just 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 5 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

Now you can check in your project and also you can get more information from here : elasticquent/Elasticquent.

Tags :
Shares