We are doing a learning exercise with Laravel 5.8 and Eloquent for developing a version of a REST api.
The database tables (company, contact & note) are rather simple in terms of their relationships:
company -> hasMany -> contacts
company -> hasOne -> note
The Model code looks like:
class Company extends Model
{
// ....
public function contacts()
{
return $this->hasMany(Contact::class);
}
public function note()
{
return $this->hasOne(Note::class);
}
}
To access each of these resources, the api is:
/api/companies
/api/notes
/api/contacts
We are wanting to return links to the foreign resources when /api/companies
is hit. e.g.:
{
"data": [
{
"id": 1,
"trading_name": "Example Company",
"_links": {
"contacts": [
"http://localhost:8100/api/contacts/1",
"http://localhost:8100/api/contacts/2",
"http://localhost:8100/api/contacts/3"
],
"notes": "http://localhost:8100/api/notes/1"
}
}
]
}
We are using Laravel's JsonResource
to format the response object.
The question is around the _links
. For the links we use the following code:
$contacts = $this->contacts->map(
function($contact) {
return route('contacts.show', [ 'contact' => $contact->id ]);
}
);
$links['contacts'] = $contacts;
$note = $this->note;
if ($note != null) {
$links['note'] = route('notes.show', [ 'note' => $note->id ]);
}
$links['self'] = route('companies.show', [ 'company' => $this->id ]);
We only get the id
field to generate the _links
array.
Is the above the way these links are generated in Laravel/Eloquent?