Handling multiple try-catches in a for loop 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')-&gt;toArray();
$departments = Department::pluck('id', 'name')-&gt;toArray();

foreach($data as $key =&gt; $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-&gt;getMessage();
    }

    // Same logic as above
    try {
        $data[$key]['department'] = $departments[$row['department']];
    } catch (\Exception $e) {
        $error_holder[$key]['department_error'] = $e-&gt;getMessage();
    }
}
You need anything here but a try catch.
foreach($data as $key =&gt; $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'] = &quot;Tower not found for $key&quot;;
    }

    if (isset($departments[$row['department']])) {
        $data[$key]['department'] = $departments[$row['department']];
    } else {
        $error_holder[$key]['tower_error'] = &quot;Department not found for $key&quot;;
    }
}

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 =&gt; $column)
    foreach($data as $key =&gt; $row) {
        if (isset($column[$row[$name]])) {
            $data[$key][$name] = $column[$row[$name]];
        } else {
            $error_holder[$key][$name.'_error'] = &quot;$name not found for $key&quot;;
        }
    }
}