在 Laravel json 响应中使用访问器和修改器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21627077/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 08:59:22  来源:igfitidea点击:

Using accessors and mutators in Laravel json responses

phpjsonangularjslaravellaravel-4

提问by tiffanyhwang

So I'm making an API that produces a json response instead of doing View::make('foo', compact('bar')).

所以我正在制作一个生成 json 响应的 API,而不是做View::make('foo', compact('bar')).

With blade templating

带刀片模板

My controller simply returns the Eloquent model for Users:

我的控制器只是返回 Eloquent 模型Users

public function index()
{
    return User::all();
}
protected function getFooAttribute()
{
    return 'bar';
}

And my view will be able to use it, along with the fooattribute (which isn't a field in the user's table).

我的视图将能够使用它以及foo属性(它不是用户表中的字段)。

@foreach($users as $user)
<p>{{$user->name}} {{$user->foo}}</p>
@endforeach

With Angular JS + json response

使用 Angular JS + json 响应

However, now that I'm not using blade but rather grabbing the jsonand displaying it with Angular JS I'm not able to do this:

但是,现在我没有使用刀片,而是json使用 Angular JS抓取并显示它,我无法做到这一点:

<p ng-repeat="user in users">{{user.name}} {{user.foo}}</p>

Is there a way to cleanly pack the json response such that I have:

有没有办法干净地打包 json 响应,以便我有:

[{"name": "John", "foo": "bar"}, ...]

Warning: I've never built an API before and I've only started programming/web dev last December. This is my attempt:

警告:我以前从未构建过 API,去年 12 月才开始编程/网络开发。这是我的尝试:

public function index()
{
  $response = User::all();
  foreach($response as $r)
  {
    $r->foo = $r->foo;
  }

  return $response;
}

回答by SamV

Yeah there is, example:

是的,例如:

return Response::json([User:all()], 200);

Usually you want more than that though..

但通常你想要的不止这些..

return Response::json([
    'error' => false,
    'data' => User:all()
], 200);

200is the HTTP Status Code.

200是 HTTP 状态代码。

To include the attributes you need to specify these attributes to automatically append onto the response in your model.

要包含属性,您需要指定这些属性以自动附加到模型的响应中。

protected $appends = array('foo');

public function getFooAttribute()
{
    return 'bar';    
}