Home > Enterprise >  How to insert array to db using create Laravel method?
How to insert array to db using create Laravel method?

Time:12-31

There is a controller method:

public function addEducation(AddPatientEducationRequest $request) {

    dd($request->all());

    $state = UserEducation::create($request->validated());
}

The dd() returns me an array that I need to insert into db:

array:1 [ // app\Http\Controllers\Api\PatientController.php:99
  "education" => array:1 [
    0 => array:5 [
      "patient_id" => 1
      "education_id" => 2
      "diplom" => "ZV 800"
      "start_date" => "2021-10-30"
      "end_date" => "2022-10-30"
    ]
  ]
]

I tried this way using loop:

foreach($request->education as $value) { UserEducation::create($value); }

CodePudding user response:

Your content looks like this:

[
    'education' => [
        //some fields
    ]
]

So, you can reach your record like this:

myArray['education'][0]

, hence your script should be

foreach($request['education'] as $value) {
    UserEducation::create($value);
}

CodePudding user response:

If education multidimensional array matches database columns then you can use the insert method like below

UserEducation::insert($request->education)

Ref :Insert Statements

CodePudding user response:

First, what's the error name ?? second, this is my suggestion I hope u will help when there is not an error name I can't help u specifically
My question is : are u add One PatientEducation mean one array of type of Model PatientEducation? if Yes . why u add a loop for adding data ?? if no . i guess u had an issue with Request form validation.

  • Related