CRUD Example Using Laravel 9 and ElasticSearch

This laravel 9 tutorial help to create CRUD rest endpoint using Elastic Search. We’ll create a rest API for add a record, edit a record , list all records and delete a records from ES database.

Nowadays, web application/tools are created on two layers, one is UI – which are created on front-end technology react, angular etc and the other is back-end which is created on backend technology like nodejs, PHP, java etc.

I have created the front-end into reactjs and the backend API is created into Laravel 9. ElasticSearch is used as a database for this project. You can create a front-end into any technology as per your project requirements.

I have already shared tutorials How To Integrate ElasticSearch With Laravel 9. I am extending this tutorial and adding CRUD operation using rest api.

Laravel CRUD API Using ElasticSearch

Let’s create a CRUD laravel API that will handle insert, update and delete elasticsearch operation. I have created ESController.php and EsService.php – This file will have all service methods that will communicate with ElasticSearch.

Open api.php file and added below entry for CRUD Operation –

//all elasticsearch data
 Route::get('es/all',  'ESController@getAllData');   
 // get single data
 Route::get('es/{id}',  'ESController@getDataById'); 
 //create a record
 Route::post('es/create',  'ESController@insertData');
 //upadte a record 
 Route::put('es/update/{id}',  'ESController@updateData');   
 delete a record 
 Route::delete('es/{id}',  'ESController@deleteData');

I have created all rest endpoints.

How To Get All Record From Elastic Search

Let’s open ESController.php file and added getAllData() method to get all record.

public function getAllData(Request $request) {      
 $from =  0;      
 $size = 200;      
 $response = $this->es_service->all($from, $size);         
 return $this->jsonpSuccess($response);    
 }

We have passed constant from and size parameter to a service method, I have created all() method into EsService.php file.

public function all($from = 0, $size = 200) {        
 $es = $this->es;        
 $params['index'] = $this->index;        
 $params['type'] = $this->type;        
 $params['size'] = $size;        
 $params['from'] = $from;        
 try {            
 $results = $es->search($params);            
 $hits = $results['hits'];            
 return $hits;        
 } catch (\Exception $ex) {  
    \Log::critical($ex);            
    $this->apiError("ES - Unable to get Entries", 400);        
 }   
}

How To Create A Record Into ElasticSearch Using Laravel

We’ll create a method into the Controller file to insert a new record into the ES database. I already added an entry into api.php file which is using POST HTTP request, we ll pass the required data into post payload.

Added below method into the ESController.php file –

public function insertData(Request $request) {      
 $parameters = $request->json()->all();           
 if(isset($parameters['type']) && $parameters['type'] != '') {      
     $response = $this->es_service->create($parameters);    
      return $this->jsonpSuccess($response);      
  } else {      
    return $this->jsonpError('Validation error(s) occurred', 400, 400, 'Data is not inserted!.');     
  }   
}

We have gotten all posted payloads data using $request->json()->all() method and send to the service create() method. Now added create() method into the service file.

public function create($input, $id = null)    {    
     $es = $this->es;
     $params['index'] = $this->index;   
     $params['type'] = $this->type;     
     $params['body'] = $input;
     try {        
      $result = $es->index($params);        
      return array("id" => $result['_id']);        
    } catch (\Exception $ex) {         
       \Log::critical($ex);         
       return $this->apiError('ES - Unable to Create Entry', 400);     
    }    
 }

Update A Record Into ElasticSearch Using Laravel

Let’s update a record in the elasticsearch database. We’ll create a method into the controller file that’ll call the service method to update the record into the database.

As per route entry, Created a PUT type HTTP request to update data, we will pass ES id into the rest endpoint and post data into the HTTP request body as a JSON format.

Let’s add the below method into the ESController.php file –

public function updateData($id, Request $request) {   
    $data = $request->json()->all(); 
     if(isset($id) && $id != '') {    
     $response = $this->es_service->update($id, $data);   
     return $this->jsonpSuccess($response);    
   } else {   
       return $this->jsonpError('Validation error(s) occurred', 400, 400, 'Pipeline request data is not updated!.');     
  }   
}

This method takes $id– ES database id and payloads as parameter. We’ll create update() method into service.

public function update($id, $input)    {     
    $es = $this->es;     
    $params['index'] = $this->index;    
     $params['type'] = $this->type;   
      $params['id'] = $id;    
     $params['body']['doc'] = $input;
         try {          
   $retUpdate = $es->update($params);        
     return array("id" => $retUpdate['_id']);       
  } catch (\Exception $ex) {         
    \Log::critical($ex);         
    return $this->apiError('ES - Unable to Update Entry', 400);       
  }   
}

We have gotten all posted payload data using $request->json()->all() method and send it to the service create() method. Now added update() method into the service file.

Delete A Record from ElasticSearch Using Laravel

Now, I will delete a record from the ElasticSearch database. We’ll create a method into the controller file that’ll call the service method to delete record from the database.

Let’s create a PUT type HTTP request to delete data, We will pass ES id into the rest endpoint.

Let’s add the below method into the ESController.php file –

public function deleteData($id) {      
    if(isset($id) && $id != '') {         
        $response = $this->self_serve_cmdb->deleteById($id);         
        return $this->jsonpSuccess($response);      
     } else {         
        return $this->jsonpError('Validation error(s) occurred', 400, 400, 'Pipeline request data is not deleted!.');      
     }    
 }

This method takes $id– ES database id and payloads as parameter. We will create update() method into service.

/**    
 * delete an entry by es     *     
 * @param string $id     
 */    
 public function deleteById($id)    {        
   $es = $this->es;        
   $params['index'] = $this->index;        
   $params['type'] = $this->type;        
   $params['id'] = $id;
   try {            
        $retDelete = $es->delete($params);            
        return array("id" => $retDelete['_id']);        
   } catch (\Exception $ex) {            
        \Log::critical($ex);            
        return  $this->apiError('ES - Unable to Delete Entry', 400);       
   }    
 }

I have ES id as a parameter for delete a record using delete() method.

Conclusion

We have learned ElasticSearch integration with laravel into first part of this tutorial, This tutorial helped to create CRUD operation for elastic-search using laravel 9. Created Rest API add a record, update a record and delete a record from elasticsearch using Laravel 9.

Leave a Reply

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