Controller function:
public function index () {
// TESTED
// The getAllActiveSuppliers() function just return Supplier::pagniate(10)
$suppliers = $this -> model -> getAllActiveSuppliers();
return new SupplierResource($suppliers);
}
Returned Json:
{
"current_page": 1,
"data": [
{
"id": 23,
"name": "Test Name",
"description": "Test Description",
"created_by": {
"id": 1,
"name": "Test 1",
"email": "[email protected]",
"email_verified_at": null,
"active": 1,
"created_at": "2018-10-12 14:17:38",
"updated_at": "2018-10-12 14:17:38"
},
"updated_by": {
"id": 1,
"name": "Test 1",
"email": "[email protected]",
"email_verified_at": null,
"active": 1,
"created_at": "2018-10-12 14:17:38",
"updated_at": "2018-10-12 14:17:38"
},
"deleted_at": null,
"created_at": "2018-10-31 01:46:11",
"updated_at": "2018-11-02 22:05:14",
}
],
...
}
What I am trying to do:
В created_by и updated_by я просто хочу показать name, email больше ничего.
What I have tried to do:
Я попытался создать коллекцию ресурсов API
Коллекция ресурсов API Supplier.php:
public function toArray($request)
{
return parent::toArray($request);
}
@TravisBritz да, извините за опечатку






Сначала вам нужно определить структуру для объекта единственное число JsonResource:
public function toArray($request)
{
return [
'id' => $this->id,
'name' => $this->name,
...
'created_by' => $this->created_by->only('name', 'email'),
...
];
}
А затем скажите своему ResourceCollection использовать класс:
Customizing The Underlying Resource Class
Typically, the
$this->collectionproperty of a resource collection is automatically populated with the result of mapping each item of the collection to its singular resource class. The singular resource class is assumed to be the collection's class name without the trailingCollectionstring.For example,
UserCollectionwill attempt to map the given user instances into theUserresource. To customize this behavior, you may override the$collectsproperty of your resource collection
(Из https://laravel.com/docs/5.7/eloquent-resources#concept-overview)
Если ваш ResourceCollection не делает ничего лишнего, возможно, он вам не понадобится. Каждый JsonResource может преобразовать себя для коллекции с помощью метода collection(), например. JsonResource::collection($models)
Проблема в том, что я возвращаю коллекцию. Пожалуйста, прочтите мой вопрос.
@Ahmedessam Я отредактировал свой ответ, чтобы применить его к коллекциям ресурсов, а не к отдельным ресурсам json.
Для тех, кому это еще может понадобиться, так как я искал себя в этой теме
Сначала создайте ресурс для вашего отношения с полями имени, адреса электронной почты.
class UserResource extends JsonResource
{
public function toArray($request)
{
return [
'name' => $this->name,
'email' => $this->email,
];
}
}
Затем создайте SupplierResource с отношением created_by к пользователю
class SupplierResource extends JsonResource
{
public function toArray($request)
{
return [
'id' => $this->id,
'name' => $this->name,
'description' => $this->description,
'created_by' => new UserResource($this->created_by)
];
}
}
В контроллере
public function index () {
$suppliers = $this->model->getAllActiveSuppliers();
return SupplierResource::collection($suppliers);
}
Думаю, мы можем добавить элемент в parent::toArray($request)
public function toArray($request)
{
$array = parent::toArray($request);
$array['created_by'] = $this->created_by->only('name', 'email');
return $array;
}
Вы имеете в виду
created_byиupdated_by?