Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

329
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!