In this post, we'll talk about how to incorporate Elasticsearch from scratch using a Laravel 9 example.
Full-text search engine Elasticsearch is deployed in real-time and has multitenant support. It offers a JSON document format and an HTTP web interface.
Table of Content
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
Elasticsearch will be installed in our system; if you haven't downloaded it yet, click here for instructions.
Step 2: Create Table using migration
We must now start a migration. In order to construct the student's table migration, we will use the command below.
php artisan make:migration create_students_table --create=students
upon successful migration. The database/migrations/create students table file needs to be modified as shown below.
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
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');
}
}
?>
Once the aforementioned file has been modified, run the command below.
php artisan migrate
Step 3: Install Package
Installing the elasticquent/elasticquent package will now be done. Consequently, first enter composer.json and add the line below.
"elasticquent/elasticquent": "dev-master"
Step 4: Add providers and aliases
In the "config/app.php" section, we will add the providers and aliases listed below.
'providers' => [
....
Elasticquent\ElasticquentServiceProvider::class,
],
'aliases' => [
....
'Es' => Elasticquent\ElasticquentElasticsearchFacade::class,
]
We will now run the following command to create an elastic search configuration file.
Step 5: Create Route
In the "routes/web.php" file, add the following route code.
<?php
use App\Http\Controllers\StudentController;
/*
|--------------------------------------------------------------------------
| 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::class, 'index']);
Route::post('studentSearchCreate',[StudentController::class, 'create']);
?>
Step 6: Create a Model and Controller
The commands listed below assist in creating the controller and model.
php artisan make:controller StudentController
php artisan make:model Student
Student.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Student extends Model
{
use HasFactory;
protected $fillable = [
'first_name','last_name', 'address'
];
}
?>
StudentController.php
<?php
namespace App\Http\Controllers;
use App\Models\Student;
use Illuminate\Http\Request;
use Response;
class StudentController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
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 \Illuminate\Http\Response
*/
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 7: Create Blade Files
In the "resources/views/" folder directory, we will create a student-search file and paste the code below.
student-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 7 Elasticsearch integration from scratch with 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($students))
@foreach($students as $key => $value)
<h3 class="text-danger">{{ $value['first_name'] }}</h3>
<p>{{ $value['last_name'] }}</p>
<p>{{ $value['address'] }}</p>
@endforeach
@endif
</div>
<div class="col-lg-6">
<div class="panel panel-default">
<div class="panel-heading">
Create New Student
</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' => 'StudentSearchCreate','autocomplete'=>'off')) }}
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>First Name:</strong>
{{ Form::text('first_name', null, array('placeholder' => 'First Name','class' => 'form-control')) }}
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>Last Name:</strong>
{{ Form::text('last_name', null, array('placeholder' => 'Last Name','class' => 'form-control')) }}
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>Address:</strong>
{{ Form::text('address', null, array('placeholder' => 'Address','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
Step 8: Run Our Laravel Application
The command listed below can be used to launch the server and run this example.
php artisan serve
Now, we'll execute our example by navigating to the URL listed below in a browser.
http://127.0.0.1:8000/studentSearch