2

I am having this model in my Laravel-5.8 project:

Employee

class Employee extends Model
{
   protected $table = 'employees';

   protected $primaryKey = 'id';

   protected $fillable = [
              'staff_code',
              'first_name',
              'last_name',
              'department_id',
          ];

  public function department()
  {
     return $this->belongsTo('App\Department','department_id');
  }    

}

That is,:

App\Employee

Also I have an external api that comes in form of JSON get request.

https://api.employees.net/allemployees

I have viewed it with postman get request and I have something like this:

 {
    "ID": "1",
    "StaffCode": "STC001",
    "FirstName": "Japheth",
    "LastName": "Shalom",
    "DepartmentCode": "dep2",
 },
 {
    "ID": "2",
    "StaffCode": "STC002",
   "FirstName": "Ahitophel",
   "last_name": "Nedum",
   "DepartmentCode": "dep1",
},
{
    "ID": "3",
    "StaffCode": "STC003",
    "FirstName": "Joash",
    "FirstName": "Nathan",
    "DepartmentCode": "dep2",
 },

and so on... this continues

Already I have created this function:

 use App\Employee;
 use App\Department;

 public function index() 
 {  
    $client = new GuzzleHttp\Client();
    $res = $client->request('GET','https://api.employees.net/allemployees');
    $clientdatas = json_decode($res, true);

   ...
 }

Apart from the id and staff_code that are UNIQUE, any of the others fields too can change from the source.

Since any of the fields can change at any time. How do I refresh the entire db, save new data and update changes?

Thank you

1
  • One way is to clear the table, and insert the new records. Another way is to check all local records by ID and check if their properties have changed coming from the API. Commented May 29, 2020 at 10:49

2 Answers 2

2

I could do something like this:

use App\Employee;
use App\Department;

public function index() 
{  
      $client = new GuzzleHttp\Client();
      $res = $client->request('GET','https://api.employees.net/allemployees');
      $clientdatas = json_decode($res->getBody()->getContents(), true);

      foreach($clientdatas as $clientdata)
      {
            $employee = Employee::firstOrNew(['id' => $clientdata['ID']]);
            $employee->staff_code = $clientdata['StaffCode'];
            $employee->first_name = $clientdata['FirstName'];
            $employee->last_name = $clientdata['LastName'];
            $employee->save();
      }
}

Every time you will make an API call, create an instance of the employee model, or get the associated model if the ID exists. Then assign the new values and save your model. This way, you will be able to either create or update the models in a single loop without any complexities.

Sign up to request clarification or add additional context in comments.

Comments

0

Don't know will it work or not but the logic you can keep.. In the other answer he is querying under a loop which is bad!

Hope It will Help you a little bit

public function index() {  
    $client = new GuzzleHttp\Client();
    $res = $client->request('GET','https://api.employees.net/allemployees');
    $clientdatas = json_decode($res->getBody()->getContents(), true);
    // create a blank array for insert
    $insert_arr = [];
    foreach($clientdatas as $clientdata) {
        $make_array = [
            'id' => $clientdata['ID'],
            'staff_code' => $clientdata['StaffCode'],
            'first_name' => $clientdata['FirstName'],
            .
            .
        ];
        array_push($insert_arr, $make_array);
        // Now the the $insert_arr will ready for insert
    }
    // Here you have to check its duplicate or not  
    $exist_in_db = Employee::all('id')->toArray(); // get the id array from db

    // do the stuff for unset the duplicate 
    $final_id = array_map(function($value) {
        return $value['id'];
    }, $team_id);
    unset($exist_in_db);
    if(count($final_id) > 0){
        foreach ($insert_arr as $key => $value) {
            if (in_array($value['id'], $final_id)) {
                unset($insert_arr[$key]);
            } else {
                array_push($final_id, $value['id']);
            }
        }
    }

    // finally insert it here
    if (count($insert_arr) > 0) {
        Employee::insert($insert_arr);    
    }
}

Let me know its helpful or not!

1 Comment

array_map(function($value) { return $value['id']; }, $team_id) is more simply array_column($team_id, 'id')

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.