Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

331
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda