Search code examples
phparraysdatabaselaravellaravel-5.5

Laravel : One to many relational data update


I have the following code :

foreach ($request->dog_vaccine_required as $key => $vaccine) {
    $serviceVaccination = \App\UserServiceVaccination::updateOrCreate([
        'user_service_id' => $id,
        'vaccine_id' => $vaccine
    ],[
        'specie' => 'Dog',
        'user_service_id' => $id,
        'vaccine_id' => $vaccine,
        'duration_6' => $request->dog_duration_6[$key],
        'duration_12' => $request->dog_duration_12[$key],
        'duration_36' => $request->dog_duration_36[$key]
    ]);
}

Now the data coming along from the form is :

Form data

It gives me exception :

Undefined offset: 2

The request dog_duration_6, dog_duration_12, dog_duration_36 arrays can be different in terms of element size,

How can i pass null to avoid exception Undefined offset: 2 ?


Solution

  • Simply add a check like to avoid offset exception.:

    isset($request->dog_duration_6[$key]) ? $request->dog_duration_6[$key] : null

    For all of them.