Reputation: 162
So I'm building a RESTful API in Laravel. So far I have a simpler controller that looks like this:
class TripController extends Controller
{
public function index()
{
$data = Trip::all();
return $data;
}
}
And I get this back:
[
{
"id": 1,
"created_at": "2015-07-06 21:01:03",
"updated_at": "2015-07-06 21:01:03",
"created_by": 1,
"updated_by": 1,
"description": "Sample Trip",
"aircraft_id": 1
}
]
Which is exactly what I asked for. The thing is 'created_by', 'updated_by', and 'aircraft_id' are foreign keys. I know I could start resolving my foreign keys using the relationships I've set up in my models, such as:
$createdByName = App\Trip::first()->createdBy()->get('name');
But this would require some looping over the collection to replace the id's with the information needed from the foreign keys (basically the names). Is there a clever way to do this in Laravel when just using it to return JSON?
Upvotes: 2
Views: 2173
Reputation: 662
If you declared the relations on the model via eloquent you could just use eager loading to deliver the related models.
Trip::with('aircraft','createdBy','updatedBy')->all();
Otherwise, if you only want to include something like the name attribute you could add an attribute to your Trip model using laravels accessor methods Define an accessor like this:
public function getAircraftNameAttribute()
{
return $this->aircraft->name;
}
And include it in the models array- or json-form by adding it to the $appends array:
protected $appends = ['aircraft_name'];
See the documentation for that here.
Upvotes: 2