简体   繁体   English

Laravel格式化JSON输出

[英]Laravel formatting JSON output

Is there a simple way to return more objects with different attribute name in JSON response? 有没有一种简单的方法可以在JSON响应中返回更多具有不同属性名称的对象?

For example I have a User model which has attributes name, password, xy and if I do return User::all(); 例如,我有一个具有属性name, password, xyUser模型,如果return User::all(); ,则return User::all(); I will return all users. 我将返回所有用户。 But what if I want to return a list of custom objects where I will return JSON format like: 但是,如果我想返回自定义对象的列表,我将在其中返回JSON格式,如:

{
    'username' : ...
    'pass': ...
    'xyz' : ...
    'from_related_model' : ...
}

so I will have name of fields returned differently then they are in DB, and also attach to each returned object an attribute from related model. 因此,我返回的字段名称将与在数据库中返回的字段名称不同,并且还将来自相关模型的属性附加到每个返回的对象。

I don't want to use mutators as I only want to return like that within one controller. 我不想使用增幅器,因为我只想在一个控制器内像这样返回。 I know I can traverse through object with foreach and make a new object by assigning values, and returning merged object. 我知道我可以使用foreach遍历对象并通过分配值并返回合并的对象来创建新对象。 But is there a simpler way to do this? 但是,有没有更简单的方法可以做到这一点?

You'll need to generate the list of objects to return manually. 您需要生成对象列表以手动返回。

Example: if you wanted to return a custom object for each user fetched from the database you could do something like the following in your controller: 示例:如果要为从数据库中获取的每个用户返回一个自定义对象,则可以在控制器中执行以下操作:

$result = [];
foreach (User::all() as $user) {
  $result[] = [
    'username' => $user->username,
    'full_name' => $user->first_name . ' ' . $user->last_name,
    'xyz' => 5,
  ];
}

return $result;

Every time you return an array or a Collection from controller method, it will be converted automatically to JSON. 每次从控制器方法返回数组或Collection时 ,它将自动转换为JSON。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM