Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

noblemfd's avatar

How to create foreign key items from external API and save into local DB

In my Laravel-5.8 project, I am having these models: Employee, Department

Employee

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

    protected $primaryKey = 'id';

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

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

 }

Department

class Department extends Model
{
   protected $table = 'departments';

   protected $primaryKey = 'id';

  protected $fillable = [
              'department_code',
          ]; 

  }

That is,:

CREATE TABLE `employees` (
 `id` int NOT NULL auto_increment,
 `staff_code` varchar(255) NOT NULL,
 `first_name` varchar(255) NOT NULL,
 `last_name` varchar(255) NOT NULL,
 `department_code` varchar(10) NOT NULL

) ENGINE=MyISAM DEFAULT CHARSET=latin1;

CREATE TABLE `employees` (
 `id` int NOT NULL auto_increment,
 `department_code` varchar(255) UNIQUE NOT NULL,

) ENGINE=MyISAM DEFAULT CHARSET=latin1;

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",
   "LastName": "Nedum",
   "DepartmentCode": "dep1",
},
{
    "ID": "3",
    "StaffCode": "STC003",
    "FirstName": "Joash",
    "LastName": "Nathan",
    "DepartmentCode": "dep2",
},

and so on... this continues

I only have the API for employee profile as shown above.

Already, I have this code:

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->department_code = $clientdata['DepartmentCode'];
        $employee->save();
     }
  }

I want to achieve these:

  1. The code should loop through departments table in the local DB, if DepartmentCode from the API does not not exist, it should first create it from the api and save into the local DB

  2. It should check each field in the api if there is any change in the allemployees, it should update the local DB on any field that has changed. Then if there is any new one it should create it. How do I achieve this?

Thank you.

0 likes
3 replies
madsem's avatar

on my phone atm but i'll try my best:

Assuming you have a belongsTo relationship set up for Department on the Employee model, you vould just do:

$employee->department()->updateOrCreate([
 'department_code' => clientdata['DepartmentCode']
], [
 'fields_to_update' => 'here',
...
]);

Or if you don't have a relationship, you can just do it in the same loop you have already, using the model facade directly:


Department::updateOrCreate([
 'department_code' => clientdata['DepartmentCode']
], [
 'fields_to_update' => 'here',
...
]);

First array in updateOrCreate is the values it checks for existence, if found it tries to update the values in second array.

If not found it will create a new row using data from both arrays

Please or to participate in this conversation.