Laravel Eloquen ORM can't return a model's relationship properly

Viewed 21

I'm creating an API. In this repository there's a method called show() where a contact is returned. The user must provide an ID of a contact and can provide an array of relationships to be loaded and an array of the contact's attributes called fields.

return $this->contacts::with($request->relationships)->findOrFail($request->id, $request->fields);

But when $request->fields is provided all the relationships return null.

Request's Json:

{
    "id": 75,
    "fields": ["id", "name"],
    "relationships": ["lead", "phone", "email", "address"]
}

Response's Json:

{
    "id": 75,
    "name": "Edgard Cesar Bertelli dos Reis",
    "lead": null,
    "phone": null,
    "email": null,
    "address": null
}

Any ideas of where I might be going wrong?

1 Answers

You must add the relations names in second parameters for findOrFail, in your example it could be like:

$fields = array_merge($request->relationships, $request->fields);
return $this->contacts::with($request->relationships)->findOrFail($request->id, $fields);
Related