Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

330
Visualizações
Laravel get data from relationship table only

I have a controller to get user but the output has relationship where the data is not come from db

Controller:

   public function test($id){

    $data = User::where("user_group_id",$id)->get();

    $tes = $data;
    return response()->json([
        'message'=>'Data Fetched',
        'payload'=>$tes,
    ],200); 
}

Output

"message" : "Data Fetched",
"payload" : [
   {
       "id":1,
       "username":asd,
       "profile":{
           "age:42"
        },
       "id":2,
       "username":sdf,
       "profile":{
           "age:60"
        },

etc

how can i access the data from the profile to group all the user by its age?

i expect the result like this logic

$data = User::all()->groupBy(profile->age);

thankyou in advance

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

You did not include the details of the relations between user and profile model but you should try something like the fallowing code to get the desired result

public function test($id)
{
  $data = User::whereHas('profile', function ($query) use($id) {
    $query->where('user_group_id',$id)
    $query->groupBy('profile.age');
  })->get();
  return response()->json(['message'=>'Data Fetched','payload'=> $data],200);
}
over 4 years ago · Santiago Trujillo Relatório

0

you can do this way also

public function test($id)
{
   $data = User::where("user_group_id",$id)->get();

   foreach($data as $one)
   {
     $one['age']=Profile::where('user_id',$one->id)->first('age');
   }
   return response()->json([
        'message'=>'Data Fetched',
        'payload'=>$tes,
    ],200);
}
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda