Laravel 7 Elasticsearch integration from scratch with example – onlinecode

Laravel 7 Elasticsearch integration from scratch with example – onlinecode

In this post we will give you information about Laravel 7 Elasticsearch integration from scratch with example – onlinecode. Hear we will give you detail about Laravel 7 Elasticsearch integration from scratch with example – onlinecodeAnd how to use it also give you demo for it if it is necessary.

In this article, we will discuss how to integrate Elasticsearch from scratch with example in laravel 7.

Elasticsearch is a real-time distributed and multitenant-capable full-text search engine. it provides HTTP web interface and JSON documents.

Overview

Step 1: Install Elasticsearch

Step 2: Create Table using migration

Step 3: Install Package

Step 4: Add providers and aliases

Step 5: Create Route

Step 6: Create a Model and Controller

Step 7: Create Blade Files

Step 8: Run Our Laravel Application

Step 1: Install Elasticsearch

We are going to install Elasticsearch in our system, If you haven’t downloaded elastic search then you can follow here.

Step 2: Create Table using migration

Now, We need to create a migration. so we will below command using create the students table migration.

PHP
php artisan make:migration create_students_table --create=students

After complete migration. we need below changes in the database/migrations/create_students_table file.

PHP
<?php

use IlluminateSupportFacadesSchema;
use IlluminateDatabaseSchemaBlueprint;
use IlluminateDatabaseMigrationsMigration;

class CreateStudentsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('students', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('first_name');
            $table->string('last_name');
            $table->text('address');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('students');
    }
}
?>

Run the below command. after the changes above file.

PHP
php artisan migrate

Step 3: Install Package

Now, We will install “elasticquent/elasticquent” package. so first open the composer.json file and add the below line.

PHP
"elasticquent/elasticquent": "dev-master"

Step 5: Add providers and aliases

We will add below providers and aliases in the “config/app.php” file.

PHP
'providers' => [
	....
	ElasticquentElasticquentServiceProvider::class,
],
'aliases' => [
	....
	'Es' => ElasticquentElasticquentElasticsearchFacade::class,
]

Now, We will generate a configuration file for elastic search using the following command.

php artisan vendor:publish --provider="ElasticquentElasticquentServiceProvider"

Step 6: Create Route

Add the following route code in the “routes/web.php” file.

PHP
<?php
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
   // return view('welcome');	
});
Route::get('studentSearch', 'StudentController@index');
Route::post('studentSearchCreate', 'StudentController@create');
?>

Step 7: Create a Model and Controller

Here below command help to create the controller and model.

PHP
php artisan make:controller StudentController
php artisan make:model Student

Student.php

PHP
<?php
namespace App;
use IlluminateDatabaseEloquentModel;
class Student extends Model
{
    //
	protected $fillable = [
        'first_name','last_name', 'address'
    ];
}
?>

StudentController.php

PHP
<?php
namespace AppHttpControllers;
use AppStudent;
use IlluminateHttpRequest;
use Response;
class StudentController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return IlluminateHttpResponse
     */
    public function index(Request $request)
    {
      if($request->has('search')){
        $students= Student::search($request->input('search'))->toArray();
      }
        return view('student-search',compact('students'));
    }
    /**
     * create student.
     *
     * @return IlluminateHttpResponse
     */
    public function create(Request $request)
    {
      $this->validate($request, [
               'first_name' => 'required',
               'last_name' => 'required',
               'address' => 'required',
        ]);
        $student= Student::create($request->all());
        $student->addToIndex();
        return redirect()->back();
    }
}
?>

Step 8: Create Blade Files

Finally, We will create student-search file in the “resources/views/” folder directory and paste the below code.

student-search.blade.php

PHP
@extends('layouts.app')
@section('content')
<div >
    <div >
        <h1  style="text-align: center;">Laravel 7 Elasticsearch integration from scratch with example</h1>
    </div>
</div>
<div >
  <div >
    <div >
      <div >
      <div >
        {{ Form::open(array('method'=>'get','class'=>'')) }}
        <div >
          <input name="search" value="{{ old('search') }}" type="text"  placeholder="Search for...">
          <span >
            <button  type="submit">Go!</button>
          </span>
        </div><!-- /input-group -->
        {{ Form::close() }}
      </div><!-- /.col-lg-6 -->
    </div><!-- /.row -->
    </div>
    <div >
        
        <div >
          <div >
            @if(!empty($students))
              @foreach($students as $key => $value)
                <h3 >{{ $value['first_name'] }}</h3>
                {{ $value['last_name'] }}</p>
                {{ $value['address'] }}</p>
              @endforeach
            @endif
          </div>
          <div >
            <div >
              <div >
                Create New Student
              </div>
              <div >
                @if (count($errors) > 0)
                <div >
                  <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' => 'StudentSearchCreate','autocomplete'=>'off')) }}
                  <div >
                              <div >
                                  <div >
                                      <strong>First Name:</strong>
                                      {{ Form::text('first_name', null, array('placeholder' => 'First Name','class' => 'form-control')) }}
                                  </div>
                              </div>
                              <div >
                                  <div >
                                      <strong>Last Name:</strong>
                                      {{ Form::text('last_name', null, array('placeholder' => 'Last Name','class' => 'form-control')) }}
                                  </div>
                              </div>
                              <div >
                                  <div >
                                      <strong>Address:</strong>
                                      {{ Form::text('address', null, array('placeholder' => 'Address','class' => 'form-control')) }}
                                  </div>
                              </div>
                          </div>
                          <div >
                            <button type="submit" >Submit</button>
                          </div>
                {{ Form::close() }}
              </div>
            </div>
          </div>
        </div>
    </div>
  </div>
</div>
@endsection

Step 9: Run Our Laravel ApplicationWe can start the server and run this example using the below command.

php artisan serve

Now we will run our example using the below Url in the browser.

http://127.0.0.1:8000/studentSearch

Please follow and like us:

Hope this code and post will helped you for implement Laravel 7 Elasticsearch integration from scratch with example – onlinecode. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs

For More Info See :: laravel And github

Leave a Comment

Your email address will not be published. Required fields are marked *

  +  10  =  14

We accept paid advance and paid guest Posting on our Site : Contact US