JayMan99
JayMan99

Reputation: 39

adding URI to laravel response

I am building an API and I have few models which have a relationship with each other:

Asset
Location
User

I am able to get objects via api by accessing /asset/5 or /location/15

This is all fine and good, now I have started to include some relations with it.. so if asset 5 is related to location 15.. the return from /asset/5 now includes (using WITH) the location info with it.

example:

/asset/5
{
    "id": 5,
--> "uri": http: //localhost/api/asset/5, <-- how do i generate/append this
     "name": null,
    "location": {
        "id": 15,
        "name": "jimUser",
-->     "uri": "http://localhost/api/location/5"  <-- how do i generate/append this
    }
}

(the URI is not part of my schema.. I want to have it added to the response.)

all of the location info is now returned with the asset. exactly what am looking for..

What I am trying to do is find a way to populate those URI fields with a link that is direct to that entity. so on the /asset/ return that contains the related location info I want to be able to provide a link that goes directly to that location.

I am unable to find a way to generate the URI for either the main response (in this case it is asset) or for a relation (in this case it is location)

I am new to Laravel and am trying to basically mirror an application that has this same type of reponse.

Any help is appreciated.

Thanks

I tried working with $request, $router and many others.

Upvotes: 1

Views: 189

Answers (1)

Erich
Erich

Reputation: 2616

Create an accessor for your uri attribute and set it to be appended automatically to the JSON response:

// Location.php

class Location
{
  protected $appends = ['uri'];

  ...

  public function getUriAttribute()
  {
    return '/api/locations/' . $this->id;
  }
}

Upvotes: 2

Related Questions