1

I want to return a JSON of an Eloquent model, but I'd like to change the array keys. By default they are set as the table field names, but I want to change them.

For example if I have a users table with two fields : id and user_name

When I return User::all(); I'll have a JSON with "[{"id" => 1, "user_name" => "bob}] etc.

I'd like to be able to change user_name to username. I haven't found the way to do it without an ugly foreach loop on the model.

4

3 回答 3

1

看看 robclancy 的presenter包,它ServiceProvider处理了你想要实现的那些事情。

GitHub 链接

于 2013-06-14T08:53:46.903 回答
1

我不确定您为什么首先要这样做,并且如果您的应用程序/最好在整个过程中使事情统一更好,会首先警告您结构。但是如果您真的想这样做..您能做:

$user = User::find($id);
return Response::json(array('id' => $user->id, 'username' => $user->user_name));

这将返回一个包含您想要的 JSON 对象。

您还可以使用以下方法更改密钥的名称:

$arr[$newkey] = $arr[$oldkey];
unset($arr[$oldkey]);
于 2013-06-14T08:48:58.530 回答
-1

只需将模型的 $hidden 静态设置为要隐藏的键:

类用户扩展 Eloquent { public static $hidden = 'id';

}

并使用 get 和 set 函数以您喜欢的方式命名它们。

于 2013-06-14T08:52:23.003 回答