Home > OS >  how to group result with json key name in laravel
how to group result with json key name in laravel

Time:10-10

user table 
 id name age 
 1  TuTu   3
 2  SuSu   4
 3  YuYu   4
 4  MoMo   4

I want to output json like this.

[
  {
    "age": 3,
    "user": [
      {
        "id": 2,
        "name": "TuTu"
      }
    ]
  },
  {
    "age": 4,
    "user": [
      {
        "id": 2,
        "name": "SuSu"
      },
      {
        "id": 3,
        "name": "YuYu"
      },
      {
        "id": 4,
        "name": "MoMo"
      }
    ]
  }
]

User::get()->groupBy("age") not working expected.

How could add json key age and user like above format in laravel?

CodePudding user response:

you can use groupBy with closur:

$value=User::get()->groupBy(function ($item){
    return 'age: '.$item->age;
});

CodePudding user response:

The answer gives you the desired output, however consider using an API Resource for JSON Response.

$response = [];

User::get()->groupBy('age')->each(function ($item, $key) use (&$response) {
    $temp = [];

    $temp['age'] = $key;

    $temp['user'] = $item->transform(function ($i, $k) {
        unset($i['age']);
        return $i;
    })->all();

    $response[] = $temp;
});

var_dump($response); // Your Output JSON
  • Related