Laravel get data from relationship table only

Viewed 122

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

2 Answers

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);
}

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);
}
Related