Hello, I have succeed to store the data in multiple table on laravel 8 using eloquent relationships. But I am not sure is this best way to do.
I have tele patient table and 3 others current_medication, Prescribed_Medication and tab_Investigations - with one to many relationship. patient_id should go on the 3 tables.
Received the data as json ojbect from fontend like this.
Patient Data: { "created_by": 1, "firstname": "Krishna", "lastname": "Thapa", "sex": "M", "smoking": "No", "alcohol": "No" }
Current Medication : [ { "drug_name": "test drug", "drug_unit": "tab", "dosage": "2 wk", "initiation_at": "2021-05-20" }, { "drug_name": "test drug 2", "drug_unit": "ph", "dosage": "1 week", "initiation_at": "2021-05-20" } ]
Lab Investigation : [ { "name": "cbc", "value": "20", "unit": "umg", "date": "2021-05-20" }, { "name": "hdl", "value": "22", "unit": "umg", "date": "2021-05-21" } ]
Prescription : [ { "p_name": "Cetamol", "p_unit": "tab", "p_dosage": "2 wk", "duration": "10" } ]
On Controller I have done like this.
public function store(Request $request)
{
$TelePatient = TelePatient::create($request->patient);
$TelMedis = $request->currMed;
$preMeds = $request->preMed;
$labInvs = $request->labInv;
foreach ($TelMedis as $Telmidi) {
$patId = ['tel_patient_id' => $TelePatient->id];
$TelMd = array_merge($Telmidi,$patId);
TeleMedication::create($TelMd);
}
foreach ($preMeds as $preMed) {
$patId = ['tel_patient_id' => $TelePatient->id];
$TelpreMed = array_merge($preMed,$patId);
TelePrescribedMedication::create($TelpreMed);
}
foreach ($labInvs as $labInv) {
$patId = ['tel_patient_id' => $TelePatient->id];
$TelLab = array_merge($labInv,$patId);
TeleLabInvestigation::create($TelLab);
}
return response()->json('The Patient data successfully added');
}
So if you have eloquent and better way. Please suggest.
Now I have to update tele_patient table, with rest 3 onetomany relationships tables. I am researching for it. If you have idea please share the eloquent best way for updating.