G
G
ganjo8882020-09-14 16:17:31
Laravel
ganjo888, 2020-09-14 16:17:31

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
          }
        }
      ]
    }

How can I get only the IDs of the tasks field? i.e. (1 and 2), I don't need the rest of the fields

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry Kim, 2020-09-17
@ganjo888

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'),
        ];
    }
}

A
Alexey Ukolov, 2020-09-14
@alexey-m-ukolov

with(['tasks' => function ($query) {
  $query->select('id');
}])

https://laravel.com/docs/8.x/eloquent-relationship...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question