php - Laravel RESTful API Resolve Foreign Keys -


so i'm building restful api in laravel. far have simpler controller looks this:

class tripcontroller extends controller {   public function index()   {     $data = trip::all();      return $data;   } } 

and 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 asked for. thing 'created_by', 'updated_by', , 'aircraft_id' foreign keys. know start resolving foreign keys using relationships i've set in models, such as:

$createdbyname = app\trip::first()->createdby()->get('name'); 

but require looping on collection replace id's information needed foreign keys (basically names). there clever way in laravel when using return json?

if declared relations on model via eloquent use eager loading deliver related models.

trip::with('aircraft','createdby','updatedby')->all(); 

otherwise, if want include name attribute add attribute trip model using laravels accessor methods define accessor this:

public function getaircraftnameattribute() {     return $this->aircraft->name; } 

and include in models array- or json-form adding $appends array:

protected $appends = ['aircraft_name']; 

see documentation here.


Comments

Popular posts from this blog

android - Pass an Serializable object in AIDL -

How to provide Authorization & Authentication using Asp.net, C#? -

How to use Authorization & Authentication in Asp.net, C#? -