Answer the question
In order to leave comments, you need to log in
How to display only the required relations fields?
There is a query where I get operations
$operation = Operation::with('tasks')->whereIn('name', ["whitelistedUri.view", 'user.view'])->get();
I receive
{
"id": 201,
"name": "user.view",
"sso_id": 6,
"tasks": [
{
"id": 2,
"pivot": {
"operation_id": 201,
"task_id": 2
}
}
]
},
{
"id": 306,
"name": "whitelistedUri.view",
"sso_id": 7,
"tasks": [
{
"id": 1,
"pivot": {
"operation_id": 306,
"task_id": 1
}
},
{
"id": 2,
"pivot": {
"operation_id": 306,
"task_id": 2
}
}
]
}
Answer the question
In order to leave comments, you need to log in
Use https://laravel.com/docs/7.x/eloquent-resources . They just simplify such work, and the controller remains clean:
class OperationController {
public function all()
{
$operations = Operation::query()
->whereIn('name', ["whitelistedUri.view", 'user.view'])
->with('tasks')->get();
return new OperationCollection($operations);
}
}
class OperationCollection extends ResourceCollection
{
public $collects = OperationResource::class;
public function toArray($request)
{
return parent::toArray($request);
}
}
class OperationResource extends JsonResource
{
/**
* @var Operation
*/
public $resource;
public function toArray($request)
{
return [
'id' => $this->resource->id,
'name' => $this->resource->name,
'sso_id' => $this->resource->sso_id,
'tasks' => $this->resource->tasks->pluck('id'),
];
}
}
with(['tasks' => function ($query) {
$query->select('id');
}])
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question