use updateOrCreate() method instead.
https://laravel.com/docs/7.x/eloquent
Then just loop over the results like you do above, and it will update whatever has changed, or create if it doesn't exist.
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
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:
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
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.
Please or to participate in this conversation.