1
\$\begingroup\$

Good day! I would like to know if this is possible to be refactored into a cleaner code. The reason I'm doing it like this is to catch the column that the error appeared on and then potentially output the column name and value for the client to view later on.

// Make the name act as the key and the value equates to ID
// $towers['tower1'] = 1;
$towers = Tower::pluck('id', 'name')->toArray();
$departments = Department::pluck('id', 'name')->toArray();
foreach($data as $key => $row) {
 try {
 // $row['tower'] = 'Hello World Tower'
 // Try to see if $row['tower'] is present in the $towers data source
 $data[$key]['tower'] = $towers[$row['tower']];
 } catch (\Exception $e) {
 // Exception occurs because index is not available
 $error_holder[$key]['tower_error'] = $e->getMessage();
 }
 // Same logic as above
 try {
 $data[$key]['department'] = $departments[$row['department']];
 } catch (\Exception $e) {
 $error_holder[$key]['department_error'] = $e->getMessage();
 }
}
asked Jun 17, 2020 at 8:49
\$\endgroup\$
1
  • 1
    \$\begingroup\$ The catch blocks will never be executed. Voting to close as not working as intended. \$\endgroup\$ Commented Jun 17, 2020 at 12:49

1 Answer 1

2
\$\begingroup\$

You need anything here but a try catch.

foreach($data as $key => $row) {
 // $row['tower'] = 'Hello World Tower'
 // Try to see if $row['tower'] is present in the $towers data source
 if (isset($towers[$row['tower']])) {
 $data[$key]['tower'] = $towers[$row['tower']];
 } else {
 $error_holder[$key]['tower_error'] = "Tower not found for $key";
 }
 if (isset($departments[$row['department']])) {
 $data[$key]['department'] = $departments[$row['department']];
 } else {
 $error_holder[$key]['tower_error'] = "Department not found for $key";
 }
}

Although you can reduce the duplication by storing sources into array and looping over it but honestly it makes the code so muddled that I don't see the benefit.

foreach (compact('tower','department') as $name => $column)
 foreach($data as $key => $row) {
 if (isset($column[$row[$name]])) {
 $data[$key][$name] = $column[$row[$name]];
 } else {
 $error_holder[$key][$name.'_error'] = "$name not found for $key";
 }
 }
}
answered Jun 17, 2020 at 12:18
\$\endgroup\$
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.