Используйте
https://laravel.com/docs/7.x/eloquent-resources. Они как раз упрощают такую работу, и контроллер остаётся чистым:
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'),
];
}
}