I have an API in Laravel, with a show(id)
method that returns a response->json($array)
. Within this function I have a foreach
, my problem is in response
, which does not wait for the foreach
to finish and then return the json. This is causing a lack of data in the view.
Is Laravel asynchronous?
My function
of the API is like this
use ...
Class ProcessesController ()
{
public function show($id){
$db = DB::connection('pgsql');
//$id = nrprocesso
$process = $db->table('processo')->where('nrprocesso',$id)
->join('viatransporte', 'viatransporte.idviatransporte', '=', 'processo.idviatransporte')
->select('processo.*','viatransporte.nmviatransporte')
->get();
//Esse processo não existe
if (!$process) {
return response()-> json([
'message' => 'Record not found process' // Esse processo não existe
], 404);
}
$idprocesso = $process[0]->idprocesso;
$idusuario = $process[0]->idusuario;
$idpessoacliente = $process[0]->idpessoacliente;
$events = $db->table('followupprocesso')->where('followupprocesso.idprocesso',$idprocesso)
->join('eventos', 'eventos.idevento', '=', 'followupprocesso.idevento')
->select('eventos.idevento', 'eventos.nmevento', 'followupprocesso.dtprevisao', 'followupprocesso.dtrealizacao', 'followupprocesso.dtprevisaoinicial', 'followupprocesso.observacao')
->get();
$dicapa = $db->table('dicapa')->where('idprocesso',$idprocesso)
->join('pessoa', 'pessoa.idpessoa', '=', 'dicapa.idpessoaexportadorrepasse')
->select('dicapa.dtregistrodi', 'dicapa.nrdeclaracaoimportacao', 'pessoa.nmpessoa')
->get();
$user = $db->table('usuario')->select('nmusuario')->where('idusuario',$idusuario)->get();
$client = $db->table('pessoa')->select('nmpessoa')->where('idpessoa',$idpessoacliente)->get();
//Alterando key do array events para o nº do evento
foreach($events as $key => $value) {
$new_key = $value->idevento;
unset($events[$key]);
$events[$new_key] = $value;
}
// for($i = 0; $i < count($events); $i ++ ){
// $value = $events[$i];
// $new_key = $events[$i]->idevento;
// unset($events[$i]);
// $events[$new_key] = $value;
// }
//Retornando resultado das consultas
$processget = [
"remotedb" => [
"process" => $process[0],
"events" => $events,
"contarray" => count($events),
"di" => $dicapa,
"user" => $user,
"client" => $client,
],
"localdb" => []
];
return response()->json($processget);
}
}
The response is not waiting for foreach
to finish the loop and then return the JSON.