简体   繁体   中英

Using accessors and mutators in Laravel json responses

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

With blade templating

My controller simply returns the Eloquent model for Users :

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

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

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

With Angular JS + json response

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

<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:

[{"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:

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

  return $response;
}

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

200 is the HTTP Status Code.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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