Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
}
like image 209
tiffanyhwang Avatar asked Feb 07 '14 11:02

tiffanyhwang


1 Answers

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';    
}
like image 77
SamV Avatar answered Oct 19 '22 03:10

SamV