i want to loop through the multiple input fields on html blade so as to be able to upload them to my database using the laravel query builder. But the problem here is that its telling me:"Attempt to read property "drugid" on string"
lets assume this is one of the html inputs:
<input type="text" name="drugname[]">
<input type="text" name="drugname[]">
<input type="text" name="drugname[]">
Next was on my controller where i looped the fields in order for it to upload to the database
public function prescribedrugs(Request $presdrug){
$validator = Validator::make($presdrug->all(), [
'consultclinic' => 'required|string',
'drugdiagnosis' => 'required|string',
'drugpassword' => 'required|string',
]);
$getuser = new Getloggedinuserservice();
$getloggedinuser = $getuser->getuser();
if ($validator->fails()) {
return response()->json([
'error' => $validator->errors()->all()
]);
}else{
$lastapptid = DB::table('AllDrugPresc')->max('Presc_Num');
$newid = $lastapptid + 1;
foreach($presdrug->drugname as $key => $d){
return DB::table('AllDrugPresc')
->insert([
'Presc_Num'=>$newid,
'Date'=>Carbon::now(),
'Time'=>date('H:i:s'),
'Drug_Id'=>$presdrug->drugid[$key],
'Drug_Name'=>$d,
'Prescription'=>$presdrug->drugprescription[$key],
'Hospital_No'=>'44455eee',
'Surname'=>'rrr',
'Other_Name'=>'rrr',
'Age'=>44,
'Sex'=>'ee',
'Account'=>'ee',
'Account_Category'=>'ddd',
'Clinic'=>$presdrug->consultclinic,
'Diagnosis'=>$presdrug->drugdiagnosis,
'Prescribed_By'=>'wwwe',
'Qty_given'=>2,
'Total_Cost'=>33
]);
}
}
}
Can someone tell me what i am doing wrong please. Thanks in advance
2
Answers
Because $presdrug->drugid is a string type, you can not use foreach. One more thing, you are using the undefined variable $newId. Try the code below:
First of all make a validated class that will validate the inputs by running php artisan make: request DrugValidationRequest
Then do the following code. Don’t insert the data using a loop. in stead of making data into loop and then insert directly
Also in the handler add the validation rule too.