Laravel : One to many relational data update - php

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 :
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 ?

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.

'duration_6' => $request->dog_duration_6[$key] ?? null,

Related

PHP Recursive Loop using UASORT on Multidimensional Array

I am writing a script that loops through a multidimensional array and it's working as hoped (sort of) but I get errors that I just can't remedy.
I am still not that comfortable building loops to manage nested arrays.
Here is my code. The goal is to sort each layer by the value of the sequence key and in the end I export the array as json.
The sequence key may or may not exist in every sub array so that may need some sort of if clause
<?php
$list = [
"key" => "book",
"sequence" => 1,
"items" => [
[
"key" => "verse",
"sequence" => 2,
"items" => [
["sequence" => 3],
["sequence" => 1],
["sequence" => 2],
],
],
[
"key" => "page",
"sequence" => 1,
"items" => [
[
"key" => "page",
"sequence" => 2,
"items" => [
["sequence" => 2],
["sequence" => 1],
["sequence" => 3],
],
],
[
"key" => "paragraph",
"sequence" => 1,
"items" => [
["sequence" => 2],
["sequence" => 1],
["sequence" => 3],
],
],
],
],
],
];
function sortit(&$array){
foreach($array as $key => &$value){
//If $value is an array.
if(is_array($value)){
if($key == "items"){
uasort($value, function($a,&$b) {
return $a["sequence"] <=> $b["sequence"];
});
}
//We need to loop through it.
sortit($value);
} else{
//It is not an array, so print it out.
echo $key . " : " . $value . "<br/>";
}
}
}
sortit($list);
echo "<pre>";
print_r($list);
?>
Here is the output and error I am getting, and I think I understand why the error is being thrown but at the same time I can not implement the proper checks needed to fix the error.
key : book
sequence : 1
key : page
sequence : 1
E_WARNING : type 2 -- Illegal string offset 'sequence' -- at line 39
E_NOTICE : type 8 -- Undefined index: sequence -- at line 39
sequence : 1
sequence : 2
sequence : 3
sequence : 1
key : page
E_WARNING : type 2 -- Illegal string offset 'sequence' -- at line 39
E_NOTICE : type 8 -- Undefined index: sequence -- at line 39
sequence : 1
sequence : 2
sequence : 3
sequence : 2
key : verse
Not that I am worried to much but another thing that I would like is the array to still be structured in the original order, ie: key, sequence, items
Using usort and array references makes it straightforward. If we're dealing with an array with a set item key, sort the item array and recurse on its children, otherwise, we're at a leaf node and can return.
function seqSort(&$arr) {
if (is_array($arr) && array_key_exists("items", $arr)) {
usort($arr["items"], function ($a, $b) {
return $a["sequence"] - $b["sequence"];
});
foreach ($arr["items"] as &$item) {
$item = seqSort($item);
}
}
return $arr;
}
Result:
array (
'key' => 'book',
'sequence' => 1,
'items' =>
array (
0 =>
array (
'key' => 'page',
'sequence' => 1,
'items' =>
array (
0 =>
array (
'key' => 'page',
'sequence' => 1,
'items' =>
array (
0 =>
array (
'sequence' => 1,
),
1 =>
array (
'sequence' => 2,
),
2 =>
array (
'sequence' => 3,
),
),
),
),
),
1 =>
array (
'key' => 'verse',
'sequence' => 2,
'items' =>
array (
0 =>
array (
'sequence' => 1,
),
1 =>
array (
'sequence' => 2,
),
2 =>
array (
'sequence' => 3,
),
),
),
),
)
Try it!
Note that the outermost structure is a root node that isn't part of an array and can't be sorted (this may be unintentional and causing confusion).

Laravel : Update if exists, If not delete | Relational data

I am updating/deleting some form data in database :
The relation is : One to Many: UserService => UserServiceVaccine
I am trying to update the table data if the form have that data, Otherwise remove if form data have not the data :
Current 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]
]);
}
It gives me offset exception. if i remove a checkbox.
What should be done.
Do you can try this ?
foreach ($request->dog_vaccine_required as $key => $vaccine) {
$shouldUpdate=isset($request->dog_duration_6[$key])&&
isset($request->dog_duration_12[$key])&&
isset($request->dog_duration_36[$key]);
if ($shouldUpdate){
$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]
]);
}else{
// Delete
}
}
I think that's a "many to many" relationship between user_service table and vaccine table.
Based on the docs here https://laravel.com/docs/5.6/eloquent-relationships#many-to-many
$serviceVaccinationArray = [];
foreach ($request->dog_vaccine_required as $key => $vaccine) {
$serviceVaccinationArray[$vaccine] = [
'vaccine_id' => $vaccine,
'specie' => 'Dog',
'duration_6' => $request->dog_duration_6[$key],
'duration_12' => $request->dog_duration_12[$key],
'duration_36' => $request->dog_duration_36[$key]
]
}
$userService = UserService::find($id);
$userService->vaccine()->sync($serviceVaccinationArray);
The sync method accepts an array of IDs to place on the intermediate table. Any IDs that are not in the given array will be removed from the intermediate table.

How do I access an arraykey of the same array I am currently in?

I've got the following problem, I'm assigning values to an array, and one of the values I'm trying to assign is dependent on a value from the same array.
Is there a way of doing it somehow LIKE this:
# this code throws a notice
$myArray = [
'keyPairs1' => [
'color' => 'green',
'...' => '...'
],
'keyPairs2' => [
'value' => $myArray['keyPairs1']['color'] === 'green' ? 'yes' : 'no', # this line
'...' => '...'
]
];
Here PHP throws me a Notice:
Notice: Undefined variable: myArray in .../somefile.php on line ...
Of course I could simply define the array first and assign something like an empty string to the value and after creating the array simply do
$myArray = [
'keyPairs1' => [
'color' => 'green',
'...' => '...'
],
'keyPairs2' => [
'value' => '', # this line
'...' => '...'
]
];
$myArray['keyPairs2']['value'] = $myArray['keyPairs1']['color'] === 'green' ? 'yes' : 'no';
but I'd rather keep it all in the array if there is any possible way to do it. The above attempt is obviously not leading to the desired result.

Get the index when combine whereIn with update Laravel

Asset_component::whereIn('id', $request->input('id'))->update(array(
'asset_status_id' => Asset_status::whereName('Waiting for transfer')->first()->id,
'technician_id' => $request->input('technician'),
'lab_id' => Asset_component::find($index)->asset->lab->id,
'office_id' => Asset_component::find($index)->asset->office->id,
'require_date' => Carbon::createFromFormat('m/d/Y', $request->input('require_date')),
'comment' => $request->input('comment'),
'warehouse_id' => null
));
I need your help to get the $index which is the id index of the loop on update function, any method that can retrieve that ? Thanks so much for your help.

PHP CodeIgniter Batch Insert Not Accepting My Array

I'm unable to get the following code to work, and it has something to do with the forming of the array. The array is actually build after a foreach() loop runs a few times, then I want to batch insert, but it comes up malformed. Why?
foreach ($results as $r) {
$insert_array = array(
'ListingRid' => $r['ListingRid'],
'StreetNumber' => $r['StreetNumber'],
'StreetName' => $r['StreetName'],
'City' => $r['City'],
'State' => $r['State'],
'ZipCode' => $r['ZipCode'],
'PropertyType' => $r['PropertyType'],
'Bedrooms' => $r['Bedrooms'],
'Bathrooms' => $r['Bathrooms'],
'YearBuilt' => (2011 - $r['Age']),
'Status' => $r['Status'],
'PictureCount' => $r['PictureCount'],
'SchoolDistrict' => $r['SchoolDistrict'],
'ListedSince' => $r['EntryDate'],
'MarketingRemarks' => $r['MarketingRemarks'],
'PhotoUrl' => (!empty($photo_url) ? $photo_url : 'DEFAULT'),
'ListingAgentFirstName' => $r['ListingAgentFirstName'],
'ListingAgentLastName' => $r['ListingAgentLastName'],
'ContactPhoneAreaCode1' => (!empty($a['ContactPhoneAreaCode1']) ? $a['ContactPhoneAreaCode1'] : 'DEFAULT'),
'ContactPhoneNumber1' => (!empty($a['ContactPhoneNumber1']) ? $a['ContactPhoneNumber1'] : 'DEFAULT'),
'ListingOfficeName' => (!empty($r['ListingOfficeName']) ? $r['ListingOfficeName'] : 'DEFAULT'),
'OfficePhoneComplete' => (!empty($o['OfficePhoneComplete']) ? $o['OfficePhoneComplete'] : 'DEFAULT'),
'last_updated' => date('Y-m-d H:i:s')
);
$insert[] = $insert_array;
}
$this->db->insert_batch('listings', $insert);
Here's the errors:
A PHP Error was encountered
Severity: Warning
Message: array_keys() [function.array-keys]: The first argument should
be an array
Filename: database/DB_active_rec.php
Line Number: 1148
A PHP Error was encountered
Severity: Warning
Message: sort() expects parameter 1 to be array, null given
Filename: database/DB_active_rec.php
Line Number: 1149
Any ideas? Thanks!
I've reduced your code to the bare minimum and it seems to work.
$i = 0;
while ($i <= 10) {
$insert_array = array(
'code' => 'asd'
);
$insert[] = $insert_array;
$i++;
}
$this->db->insert_batch('group', $insert);
You should check the elements of the array, comment them all and de-comment them one by one until you got the culprit.
Looks like you need to wrap your array in a second array. You're supposed to provide an array of row arrays.
$insert_array = array(array(...));

Categories