I am building a form which the user fills and then I save it into the db. Then I retrieve users who match the criteria and for each one of them I store into another table and also send them an email.
$userModel = new User();
$currentUser = $userModel->findUserById($user->id);
$requestModel = new Requests();
$success = $requestModel->saveRequest($currentUser->usr_id, $tagId, $title, $task, $fixed, $price, $hour, $quality, $multiple, $datetime, $postal, $cityId, $travel);
if($success){
$request = $requestModel->getUserLatestRequest($currentUser->usr_id);
if($request){
$user = new User();
$alluserids= $user->getAllSkillCityUserIds($cityId, $tagId);
$targetId = (array_column($alluserids, 'usr_id'));
//error_log("<pre>targetId".print_r($targetId,true)."</pre>");
foreach($targetId as $target) {
if($target == $currentUser->usr_id){
continue;
}
$lead = new RequestsLead();
$lead->addRequest($request->req_id, $request->req_userid, $target);
$contractor = $userModel->findUserbyId($target);
$nemail = new NotificationsEmail();
$nemail->sendGotRequest($contractor->usr_email, $contractor->usr_firstname);
}
}
$this->flash->success('<div data-toggle="notify" data-onload data-message="Thanks for using our service!." data-options="{"status":"success"}" class="hidden-xs"></div>');
$this->response->redirect($this->url->get(""));
}else{
$this->flash->error('<div data-toggle="notify" data-onload data-message="Sorry! Please try again." data-options="{"status":"danger"}" class="hidden-xs"></div>');
$this->response->redirect($this->url->get("request"));
}
The problem comes when there are alot of users and this function will need to finish running before the user is redirected back to the page with the flash message. How can I modify this so I redirect the user back to the page with the flash message first then run the php foreach functions storing into the db and sending emails?
I tried switching the order of the functions but once the user is redirected the php functions stopped proceeding.